If you want to maintain an ordered dictionary with json file in Python, this post might help.
As we known, Python dictionaries are unordered, but we got OrderedDict.
First of all, we have to use that to make sure the given dict is ordered.1
2
3
4from collections import OrderedDict
givendict = OrderedDict()
givendict["key1"] = "val1"
givendict["key2"] = "val2"
If we give the ordered dict to json.dumps() directly, the fields in that json file are still in the wrong order.
A simple way to preserving the order of a mappling in JSON is:1
Json.dumps([givendict])
The content of the json file will be like:1
[{"key1": "val1", "key2": "val2"}]
When we tried to load the data from json file, we have to remove the “[]” firstly.1
2
3
4chars = "[]"
for ch in chars:
if ch in data:
data = data.replace(ch, "")
Now it’s time to load the data, but the json.loads will still mess up order if you didn’t add the arg as below:1
outordereddict = json.loads(data, object_pairs_hook=OrderedDict)