simplejson returns values not in order [duplicate]

帅比萌擦擦* 提交于 2019-12-13 01:43:47

问题


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?


回答1:


I sometimes need to send the information strictly in order. Don't use a dictionary then, use a list of tuples:

values = [("entry1", "value1"), ("entry2", "value2"), ("entry3", "value3")]

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:

An object is an unordered collection of zero or more name/value pairs [...]

and the Python dict.items() documentation:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.




回答2:


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




回答3:


You can use the sort_keys=True option in dumps:

simplejson.dumps(values, sort_keys=True)

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.




回答4:


This not problem with simplejson, its the behavior of dict in python. dicts 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:

values = [ {"entry1":"value1"}, { "entry2":"value2"} ,{"entry3":"value3"} ]

or

values = [ {"key":"entry1", "value":"value1"},
           {"key":"entry2", "value":"value2"},
           {"key":"entry3", "value":"value3"}
         ]


来源:https://stackoverflow.com/questions/17789355/simplejson-returns-values-not-in-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!