About Field Order in JSON Structures

If you want to preserve the field order in the JSON string that you are building in Python before 3.6, use OrderedDict instead of dict to build up the dictionary:

1
2
3
4
5
6
7
8
9
import json
from collections import OrderedDict

song = OrderedDict([
    ("title", "Yu Mountain"), 
    ("artist", "Plaid"), 
    ("length", "4:04"),
])
json.dumps(song)

Since Python 3.6, the order of the keys and values is preserved for standard dictionaries.

Tips and Tricks Programming Python 3