我正在使用json module创建一个包含类似条目的json文件

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

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

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

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

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

推荐答案

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

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)的一个好方法是输出一个(键、值)对数组,您可以在阅读时将其转换回有序映射:

>>> 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 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: 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相关问答推荐

Vega-Lite时钟(使用Vega-Lite中的计时器)

Jolt将键和值转换为单独的数组集

Terraform迭代JSON文件以获取键值对

将PNG图像保存为Python中的JSON文件

Jolt Spec 跳过数组中的第一个元素

爆炸没有数组的 struct pyspark

Python 将 struct 化文本转换和筛选为对象

如何强制仅有一个元素的数组在JSON中生成方括号

将 JSON 文件放在哪里以在 Angular 8 应用程序中加载静态 JSON 数据?

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

如何使用 Swiftui 判断 JSON 是否缺少键值对

如何使用 gson 调用默认反序列化

苗条的 JSON 输出

IE中Json响应下载(7~10)

Spring Security 和 JSON 身份验证

gson:将 null 视为空字符串

如何让 javascript 从 .json 文件中读取?

使用新的 Net Core 3.0 Json 时忽略属性

如何使用 Jackson 的 objectMapper 反序列化接口字段?

如果键可能不存在,则从 Python dict 读取