json.dumps弄乱顺序 [英] json.dumps messes up order

查看:743
本文介绍了json.dumps弄乱顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 json模块创建一个json文件包含喜欢的条目

I'm working with the json module creating a json file containing entries of the like

json.dumps({"fields": { "name": "%s", "city": "%s", "status": "%s", "country": "%s" }})

但是,在创建的json文件中,字段顺序错误

However, in the json-file created the fields are in the wrong order

{"fields": {"status": "%s", "city": "%s", "name": "%s", "country": "%s"}}

这是一个问题,因为%s-字符串的替换现在不正确.

which is a problem because the substitions for the %s-strings are now incorrect.

如何强制dumps函数保持给定顺序?

How can I force the dumps function to keep the given order?

推荐答案

就像其他答案正确指出的那样,在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.

这篇关于json.dumps弄乱顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆