Search code examples
pythonjsonordereddictionary

Python JSON input order


I am attempting to read a JSON file containing data which I want to keep in order as it is a mathematical equation which can't change. I have tried using OrderedDict() however this doesn't work (or I can't get it to work).

Here is the code I am using:

import json
from collections import OrderedDict

json_data = open('example3.json')
data = OrderedDict(json.load(json_data))

print (json.dumps(data))

Could anyone shine some light as to why this is not working?

Kind regards Craig


Solution

  • json.load will load the json data into a dictionary. You then convert this dictionary to an OrderedDict. Unfortunately, because it was a dictionary first the order could have already changed before it is "set" in the OrderedDict.

    To load the json directly into an OrderedDict you can use the keyword argument object_pairs_hook with OrderedDict. See the documentation for more details.

    import json
    from collections import OrderedDict
    
    json_data = open('example3.json')
    data = json.load(json_data, object_pairs_hook=OrderedDict)