As others have said, dict disordered. collections.OrderedDict is a subclass of dict whose keys are ordered. The problem is that json.load returns the dict directly, and we cannot just throw the result into the OrderedDict , since the order of the keys has already lost information at this point.
We need a way to tell json.load to return an OrderedDict instead of a dict . This can be done by implementing a custom json.JSONDecoder that supplies object_pairs_hook . object_pairs_hook receives the JSON object as a list of tuples (key, value) in the order they appear in the JSON document. It should return a translation of this object into a Python object. We will pass this list of tuples to the initializer for collections.OrderedDict , and this should do the trick.
Here is the code:
data = """ { "foo": "bar", "a_list": [1, 2, 3], "another_object": { "c": 3, "a": 1, "b": 2 }, "last_key": 42 } """ decoder = json.JSONDecoder(object_pairs_hook=collections.OrderedDict) result = decoder.decode(data) print(result)
which gives:
OrderedDict([('foo', 'bar'), ('a_list', [1, 2, 3]), ('another_object', OrderedDict([('c', 3), ('a', 1), ('b', 2)])), ('last_key', 42)])
Finally, you might be wondering: "Why is there so much extra work?" Well, JSON should not be considered as a data structure with any fixed order. You go against the grain by doing this.