simplejson返回不按顺序的值 [英] simplejson returns values not in order
问题描述
在Django中使用 simplejson
时,我有时需要按顺序发送信息。
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")
这就是返回
{"entry2": "value2", "entry3": "value3", "entry1": "value1"}
但是我希望它返回:
{"entry1":"value1","entry2":"value2","entry3":"value3"}
如何在 simplejson
中按顺序发送信息?
How can I send the information in order in simplejson
?
推荐答案
我有时需要严格按照发送信息。不要使用字典,请使用元组列表:
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")]
JSON对象没有设置顺序,字典和。也不会保留您的输入顺序,也不需要。
Dictionaries and JSON objects do not have a set order. Neither will preserve your input order, nor are they required to.
引用 JSON RFC :
一个对象是零个或多个名称/值对的无序集合[ ...]
An object is an unordered collection of zero or more name/value pairs [...]
和Python dict.items()
文档:
and the Python dict.items()
documentation:
键和值以任意顺序列出,这是非随机的,因Python实现而异,并且取决于字典的插入和删除历史。
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.
这篇关于simplejson返回不按顺序的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!