Python – JSON output sorting in Python

jsonpythonsorting

I've a problem with JSON in python.

In fact, if I try to execute this code, python gives me a sorted JSON string!

For example:

values = {
  'profile': 'testprofile',
  'format': 'RSA_RC4_Sealed',
  'enc_key': base64.b64encode(chiave_da_inviare),
  'request': base64.b64encode(data)
}

values_json = json.dumps(values, sort_keys = False, separators = (',', ':'))

And this is the output:

{
  "profile": "testprofile",
  "enc_key": "GBWo[...]NV6w==",
  "request": "TFl[...]uYw==",
  "format": "RSA_RC4_Sealed"
}

As you can see, I tried to use "sort_keys=False" but nothing changed.

How can I stop Python sorting my JSON strings?

Best Answer

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