python - 加扰的 JSON 字符串

标签 python json

我正在尝试使用 json python 模块构建 JSON 字符串。

我特别想要这个结构:

data = {
    'Id' : deviceId,
    'UnixTime' : unixTime,
    'Temp' : round( temperature, 2 ),
    'Rh' : round( humidity,2 ),
}

但是当我执行:jsonString = json.dumps( data )

所有字段均已打乱。

有什么建议吗?

最佳答案

Python dict 和 JSON 对象都是无序集合。

使用 sort_keys 参数对键进行排序:

>>> import json
>>> json.dumps({'a': 1, 'b': 2})
'{"b": 2, "a": 1}'
>>> json.dumps({'a': 1, 'b': 2}, sort_keys=True)
'{"a": 1, "b": 2}'

如果您需要特定订单;你可以使用collections.OrderedDict:

>>> from collections import OrderedDict
>>> json.dumps(OrderedDict([("a", 1), ("b", 2)]))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict([("b", 2), ("a", 1)]))
'{"b": 2, "a": 1}'

关于python - 加扰的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42509327/

相关文章:

python - 列表元组 - SETOF 记录的 Python/PostgreSQL 返回类型

python - 按完整路径导入具有相似内部模块名称的 python 包

java - 将字符串值转换为类型

android - Parse.com 从云 clode 函数接收 JSON 数组

Javascript:重组 JSON

python - 如何在选中时获取 Checkbutton 的状态?

python - 如何跟踪执行中的父/子交易

json - 在 Serilog 中,如何在使用 {Properties} 格式说明符时从 JSON 格式的日志消息中删除空括号?

javascript - PHP json_encode 返回未转义的 '

php - 如何以编程方式编写 nslookup?