JSON对象中的项目是否使用“json.ddump”出现故障?我在用json.dumps转换成jsoncountries.append({"id":row.id,"name":row.name,"timezone":row.timezone})print json.dumps(countries)我的结果是:[
{"timezone": 4, "id": 1, "name": "Mauritius"},
{"timezone": 2, "id": 2, "name": "France"},
{"timezone": 1, "id": 3, "name": "England"},
{"timezone": -4, "id": 4, "name": "USA"}]我希望按以下顺序设置键:ID、Name、Timezone-但我有时区、id、name。我该怎么解决这个问题?
3 回答
小怪兽爱吃肉
TA贡献1852条经验 获得超1个赞
dict
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 3.6以来
>>> json.dumps(OrderedDict(a=1, b=2))'{"a": 1, "b": 2}'>>> json.dumps(OrderedDict(b=2, a=1))'{"b": 2, "a": 1}'
OrderedDict
object_pair_hook
>>> json.loads('{"a": 1, "b": 2}', object_pairs_hook=OrderedDict)OrderedDict([('a', 1), ('b', 2)]) >>> json.loads('{"b": 2, "a": 1}', object_pairs_hook=OrderedDict)OrderedDict([('b', 2), ('a', 1)])
料青山看我应如是
TA贡献1772条经验 获得超8个赞
>>> {"b": 1, "a": 2}{'a': 2, 'b': 1}
json.dumps
:
>>> {"id":1,"name":"David","timezone":3}{'timezone': 3, 'id': 1, 'name': 'David'}
添加回答
举报
0/150
提交
取消