views:

165

answers:

5

Hi

i've a problem with JSON in python.

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

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?

thanks!

+2  A: 

The keys aren't sorted: "profile", "enc_key", "request", "format".

It sounds like you want them to appear in the same order that you created them in the dictionary, but dictionaries are inherently unsorted, they don't remember the order you inserted keys.

There are a number of SortedDict implementations that you can use, but the json encoder won't know to use it to get the keys in the order you want.

Ned Batchelder
A: 

Which version of python are you running? Because mine has no attribute sort_keys and it does not sort.

Enrico Carlesso
+6  A: 

You are storing your values into a python dict which has no inherent notion of ordering at all, it's just a key => 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?

Joe
because i think that my code doesn't work because the order is not the right. is it possible?
Ldn
You code is working fine, its just that the order is undefined. If you want to always be consistent use "sort_keys=True".
Joe
thanks! i've solved!! you rock ;)
Ldn
+1  A: 

If you specify sort_keys=False then Python will simply print the items in whatever order they appear in the underlying Python dict object. In some cases this may happen to be the same as the default alphanumeric sort order. In your example, the keys AREN'T even sorted like that, since "format" comes after "request". Regardless, the sort_keys parameter is still valid, as evidenced by this sample code:

>>> import json
>>> json.dumps({"a":5, "b":6, "c":7}, sort_keys=False)
'{"a": 5, "c": 7, "b": 6}'
Eli Courtwright
A: 

If you rely on the order of the keys and values in a JSON object you are doing something very wrong.

DasIch
that should be a comment
SilentGhost