When I'm using python's requests
module this way:
response = requests.get('http://[some_api_url]')
print response.json()
I get different json ordered in contrary to viewing the json via browser.
For example:
Via response.json() I get:[{"key2":"value2"},{"key1:"value1"}]
Whereas via browser I see it as supposed to be:
[{"key1:"value1"},{"key2":"value2"}]
EDIT: When printing response.text
its in the right order
But not json
You can use the object_pairs_hook
argument of 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 the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict() will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.
import json
from collections import OrderedDict
result = json.loads(request.text,
object_pairs_hook=OrderedDict)
To get simpler, you can see in the implementation of requests that kwargs are passed from the json method to the json module, hence this works as well:
d = response.json(object_pairs_hook=OrderedDict)
and d
will be an OrderedDict
with the order of response.text
preserved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With