Requests the json return module with unordered elements

When I use the python requests module as follows:

response = requests.get('http://[some_api_url]') print response.json() I get different json ordered as opposed to viewing json through a browser.

For instance:
Through response.json (), I get:
[{"key2":"value2"},{"key1:"value1"}]

While through the browser I see this as intended: [{"key1:"value1"},{"key2":"value2"}]

EDIT: When printing response.text it in the correct order But not json

+6
source share
1 answer

You can use the object_pairs_hook argument for the json module, as suggested in the doc :

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of dict. This function can be used to implement custom decoders that rely on the decoding order of key pairs and values ​​(for example, collection.OrderedDict () will remember the insertion order). If object_hook is also defined, object_pairs_hook takes precedence.

 import json from collections import OrderedDict result = json.loads(request.text, object_pairs_hook=OrderedDict) 

To simplify, you can see in the query implementation that kwargs are passed from the json method to the json module, so this works as well:

 d = response.json(object_pairs_hook=OrderedDict) 

and d will be OrderedDict keeping the order of response.text .

+15
source

All Articles