在 Django 中使用 simplejson
时,有时我需要严格按顺序发送信息。
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
中按顺序发送信息?
I sometimes need to send the information strictly in order.
那么不要使用字典,使用元组列表:
values = [("entry1", "value1"), ("entry2", "value2"), ("entry3", "value3")]
字典和 JSON 对象没有固定的顺序。既不会保留您的输入顺序,也不需要保留。
引用JSON RFC :
An object is an unordered collection of zero or more name/value pairs [...]
和 Python dict.items()
文档:
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.