我正在尝试使用 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/