Python json.dumps 弄乱了顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30152688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
json.dumps messes up order
提问by TheWaveLad
I'm working with the json modulecreating a json
file containing entries of the like
我正在使用json 模块创建一个json
包含类似条目的文件
json.dumps({"fields": { "name": "%s", "city": "%s", "status": "%s", "country": "%s" }})
However, in the json
-file created the fields are in the wrong order
但是,在json
创建的-file 中,字段顺序错误
{"fields": {"status": "%s", "city": "%s", "name": "%s", "country": "%s"}}
which is a problem because the substitions for the %s
-strings are now incorrect.
这是一个问题,因为%s
-strings 的替换现在不正确。
How can I force the dumps
function to keep the given order?
如何强制dumps
函数保持给定的顺序?
采纳答案by Eric O Lebigot
Like the other answers correctly state, before Python 3.6, dictionaries are unordered.
就像其他正确的答案一样,在 Python 3.6 之前,字典是unordered。
That said, JSON is also supposed to have unorderedmappings, so in principle it does not make much sense to store ordered dictionaries in JSON. Concretely, this means that upon reading a JSON object, the order of the returned keys can be arbitrary.
也就是说,JSON 也应该具有无序映射,因此原则上将有序字典存储在 JSON 中没有多大意义。具体来说,这意味着在读取 JSON 对象时,返回的键的顺序可以是任意的。
A good way of preserving the order of a mapping (like a Python OrderedDict) in JSON is therefore to output an array of (key, value) pairs that you convert back to an ordered mapping upon reading:
因此,在 JSON 中保留映射顺序(如 Python OrderedDict)的一种好方法是输出一个 (key, value) 对数组,在读取时将其转换回有序映射:
>>> from collections import OrderedDict
>>> import json
>>> d = OrderedDict([(1, 10), (2, 20)])
>>> print d[2]
20
>>> json_format = json.dumps(d.items())
>>> print json_format # Order maintained
[[1, 10], [2, 20]]
>>> OrderedDict(json.loads(json_format)) # Reading from JSON: works!
OrderedDict([(1, 10), (2, 20)])
>>> _[2] # This works!
20
(Note the way the ordered dictionary is constructed from a listof (key, value) pairs: OrderedDict({1: 10, 2: 20})
would not work: its keys are not necessarily ordered as in the dictionary literal, since the literal creates a Python dictionary whose keys are unordered.)
(请注意有序字典是从(key, value) 对列表构造的方式:OrderedDict({1: 10, 2: 20})
行不通:它的键不一定像字典文字中那样有序,因为文字创建了一个 Python 字典,其键是无序的。)
PS: Starting with Python 3.1, the json modules offers a hookfor automatically converting a list of pairs (like above) to something else like an OrderedDict.
PS:从 Python 3.1 开始,json 模块提供了一个钩子,用于将对列表(如上)自动转换为其他内容,如 OrderedDict。
回答by ShacharSh
This is a dictionary, and dictionaries don't keep order. You can use OrderedDictinstead.
这是一本字典,字典不保持秩序。您可以改用OrderedDict。
You could also add the sort_keys=False parameter:
您还可以添加 sort_keys=False 参数:
json.dumps(values, sort_keys=False)
回答by Ajay
You cannot create an OrderedDict from a dict because order has already changed the moment you create a dictionary.So best way is to use tuples to create a OrderedDict
您不能从 dict 创建 OrderedDict 因为在您创建字典的那一刻顺序已经改变。所以最好的方法是使用元组来创建 OrderedDict
from collections import OrderedDict
import json
a = (("name","foo"),("city","bar"),("status","baz"),("country","my"))
b = OrderedDict(a)
c = {"fileds": b}
print json.dumps(c)
Output:
{"fileds": {"name": "foo", "city": "bar", "status": "baz", "country": "my"}}
回答by Antony Hatchkins
You can choose OrderedDict
to be used instead of an ordinary dict
when creating a json object to remember the order of insertions:
创建json对象时可以选择OrderedDict
使用代替普通的dict
来记住插入的顺序:
>>> from collections import OrderedDict
>>> a = '{"fields": { "name": "%s", "city": "%s", "status": "%s", "country": "%s" }}'
>>> b = json.loads(a, object_pairs_hook=OrderedDict)
>>> json.dumps(b)
'{"fields": {"name": "%s", "city": "%s", "status": "%s", "country": "%s"}}'