1

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

Craig
  • 675
  • 1
  • 7
  • 23
  • 1
    Just note that the json spec explicitely mentions that json objects (which translate to `dict`s in Python) are "an _unordered_ collection of key:value pairs" - IOW, you should __not__ rely on keys order in json. – bruno desthuilliers Jan 06 '15 at 11:45

1 Answers1

3

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)
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125