This question already has an answer here:
When working with simplejson
in Django, I sometimes need to send the information strictly in order.
values = {"entry1":"value1","entry2":"value2","entry3":"value3"}
return HttpResponse(simplejson.dumps(values),content_type="application/json")
That's what it returns
{"entry2": "value2", "entry3": "value3", "entry1": "value1"}
But I want it to returns this instead:
{"entry1":"value1","entry2":"value2","entry3":"value3"}
How can I send the information in order in simplejson
?
You can use the
sort_keys=True
option in dumps:which will print out your dictionary with the keys in sorted order. However, dictionaries are inherently unordered, so when you give the dictionary as a parameter to
HttpResponse
, the results won't be in order.The traditional way of solving this issue is by using 2-dimensional tuple/list, as suggested by Martjin Pieters.
The more Pythonic way of accomplishing this is by using OrderedDict, however.
For similar question/solution see: Can I get JSON to load into an OrderedDict in Python?
For OrderedDict documentation see: http://docs.python.org/2/library/collections.html#collections.OrderedDict
I sometimes need to send the information strictly in order. Don't use a dictionary then, use a list of tuples:
Dictionaries and JSON objects do not have a set order. Neither will preserve your input order, nor are they required to.
To quote the JSON RFC:
and the Python
dict.items()
documentation:This not problem with
simplejson
, its the behavior ofdict
in python.dict
s are not ordered, so you can't really predict in what order they will come.You can reformat your data to get that in order as:
or