且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

json.dumps弄乱顺序

更新时间:2023-09-11 21:54:04

就像其他答案正确指出的那样,在Python 3.6之前,字典是 unordered .

Like the other answers correctly state, before Python 3.6, dictionaries are unordered.

也就是说, JSON还应该具有无序映射,因此从原理上讲将有序字典存储在JSON中并没有多大意义.具体来说,这意味着在读取JSON对象时,返回键的顺序可以是任意的.

That said, JSON is also supposed to have unordered mappings, 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中保留映射顺序(例如Python OrderedDict)的一种好方法是输出(键,值)对的数组,您在阅读时将其转换回有序映射:

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:

>>> 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

(请注意,从(键,值)对的列表中构造有序字典的方式:OrderedDict({1: 10, 2: 20})不起作用:其键不一定像字典文字中那样排序,因为该文字会创建一个Python字典,其字典是无序的.)

(Note the way the ordered dictionary is constructed from a list of (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.)

PS :从Python 3.1开始,json模块

PS: Starting with Python 3.1, the json modules offers a hook for automatically converting a list of pairs (like above) to something else like an OrderedDict.