JSON output sorting in Python JSON output sorting in Python json json

JSON output sorting in Python


Try OrderedDict from the standard library collections:

>>> import json>>> from collections import OrderedDict>>> values = OrderedDict([('profile','testprofile'),                           ('format', 'RSA_RC4_Sealed'),                           ('enc_key', '...'),                           ('request', '...')])>>> json.dumps(values, sort_keys=False)'{"profile": "testprofile", "format": "RSA_RC4_Sealed", "enc_key": "...", "request": "..."}'

Unfortunately this feature is New in version 2.7 for collections


You are storing your values into a Python dict which has no inherent notion of ordering at all, it's just a key-to-value map. So your items lose all ordering when you place them into the values variable.

In fact the only way to get a deterministic ordering would be to use sort_keys=True, which I assume places them in alphanumeric ordering. Why is the order so important?


An OrderedDict as discussed elsewhere is most of the solution to your problem, and an 'ObjDict' could be even better.

However if you need the order maintained on loading, then you will also need the json.loads() to load the values into an OrderedDict. To do this use

from collections import OrderedDictvalues=json.loads(jsontext,object_pairs_hook=OrderedDict)

Otherwise even though the json file will be in order, that order will be lost when loaded.

Perhaps an even better solution is to use 'ObjDict' in place of OrderedDict.This requires a pip install objdict. ObjDict still maintains order, as with OrderedDict, but also brings JSON support and better handling of this example.

from objdict import ObjDictvalues = ObjDict("""{"profile" : "testprofile",      "format": "RSA_RC4_Sealed" }""")values.enc_key = base64.b64encode(chiave_da_inviare)values.request = base64.b64encode(data)values_json = values.dumps(separators=(',', ':'))