JSON output sorting in Python

Solution 1:

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

Solution 2:

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?