If you want to maintain an ordered dictionary with json file in Python, this post might help.

1. Ordered Dictionary

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
4
from collections import OrderedDict
givendict = OrderedDict()
givendict["key1"] = "val1"
givendict["key2"] = "val2"

2. Json.dumps()

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"}]

3. Remove [] from the json file

When we tried to load the data from json file, we have to remove the “[]” firstly.

1
2
3
4
chars = "[]"
for ch in chars:
if ch in data:
data = data.replace(ch, "")

4. Json.loads()

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)