Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.loads() doesn't keep order [duplicate]

I have formatted my String to look like JSON so I could do json.loads on it. When I printed on the screen it turned out it messed up the order. I know that Python dictonaries are not ordered but is there ANY way to keeps this order? I really need to keep it. Thanks!

like image 732
shurrok Avatar asked Nov 04 '17 13:11

shurrok


Video Answer


1 Answers

Both JSON en Python dictionaries (those are JSON objects) are unordered. So in fact it does not makes any sense to do that, because the JSON encoder can change the order.

You can however define a custom JSON decoder, and then parse it with that decoder. So here the dictionary hook willl be an OrderedDict:

from json import JSONDecoder
from collections import OrderedDict

customdecoder = JSONDecoder(object_pairs_hook=OrderedDict)

Then you can decode with:

customdecoder.decode(your_json_string)

This will thus store the items in an OrderedDict instead of a dictionary. But be aware - as said before - that the order of the keys of JSON objects is unspecified.

Alternatively, you can also pass the hook to the loads function:

from json import loads
from collections import OrderedDict

loads(your_json_string, object_pairs_hook=OrderedDict)

Update: as of python-3.7, a dictionary retains insertion order. So if one uses python-3.7, the standard json.load and json.loads should work fine. Note however that a JSON object is still unordered, so that the JavaScript end can load/dump the object in any order.

like image 108
Willem Van Onsem Avatar answered Oct 13 '22 00:10

Willem Van Onsem