Playing with json in Python’s STL and came up with this..
import json as j
cred = j.dumps({'Name': 'John Doe', 'Occupation': 'Programmer'},
sort_keys = True,
indent = 4,
separators = (',', ': '))
_f = open('credentials', 'w')
_f.write(cred)
_f.close()
The output is below and all is fine..
{
"Name": "John Doe", "Occupation": "Programmer"}
However, i accidentally typed name in lowercase like this..
cred = j.dumps({'name': 'John Doe', 'Occupation': 'Programmer'},
sort_keys = True,
indent = 4,
separators = (',', ': '))
and the result was this..
{
"Occupation": "Programmer", "name": "John Doe"}
How does json determine the write/output order of the values passed to it, what precedence does uppercase have over lowercase or vice versa and is there a way to preserve order?
Python dictionaries, as well as JSON objects, do not have an order. Any order you might see is arbitrary and may change at any time. If you want to store order in JSON, you’ll need to use an array instead of an object.
sort_keysseems to guarantee some sort of output order, but that’s likely only to make it more readable for humans. Computers reading JSON shouldn’t care about field order.