Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

requests module return json with items unordered

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

like image 293
JavaSa Avatar asked Jan 27 '16 16:01

JavaSa


1 Answers

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.

like image 56
stellasia Avatar answered Oct 30 '22 15:10

stellasia