Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get JSON to load into an OrderedDict?

Ok so I can use an OrderedDict in json.dump. That is, an OrderedDict can be used as an input to JSON.

But can it be used as an output? If so how? In my case I'd like to load into an OrderedDict so I can keep the order of the keys in the file.

If not, is there some kind of workaround?

like image 927
c00kiemonster Avatar asked Aug 03 '11 04:08

c00kiemonster


People also ask

Does JSON loads preserve order?

loads() doesn't keep order [duplicate] Bookmark this question. Show activity on this post.

What is JSON load ()?

load() json. load() takes a file object and returns the json object. It is used to read JSON encoded data from a file and convert it into a Python dictionary and deserialize a file itself i.e. it accepts a file object.


1 Answers

Yes, you can. By specifying the object_pairs_hook argument to JSONDecoder. In fact, this is the exact example given in the documentation.

>>> json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode('{"foo":1, "bar": 2}') OrderedDict([('foo', 1), ('bar', 2)]) >>>  

You can pass this parameter to json.loads (if you don't need a Decoder instance for other purposes) like so:

>>> import json >>> from collections import OrderedDict >>> data = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict) >>> print json.dumps(data, indent=4) {     "foo": 1,     "bar": 2 } >>>  

Using json.load is done in the same way:

>>> data = json.load(open('config.json'), object_pairs_hook=OrderedDict) 
like image 71
SingleNegationElimination Avatar answered Oct 07 '22 19:10

SingleNegationElimination