我正在使用“json.loads()”将json数据转换为python字典,但是输出与原始json数据的顺序不同。
JSON
{
"cam":{
"cam1":{"dly":11,"val":12,"alg":13,"blk":14},
"cam2":{"dly":21,"val":22,"alg":23,"blk":24},
"cam3":{"dly":31,"val":32,"alg":33,"blk":34},
"cam4":{"dly":41,"val":42,"alg":43,"blk":44},
"cam5":{"dly":51,"val":52,"alg":53,"blk":54},
"cam6":{"dly":61,"val":62,"alg":63,"blk":64},
"cam7":{"dly":71,"val":72,"alg":73,"blk":74},
"cam8":{"dly":81,"val":82,"alg":83,"blk":84},
"cam9":{"dly":91,"val":92,"alg":93,"blk":94},
"cam10":{"dly":101,"val":102,"alg":103,"blk":104},
"cam11":{"dly":111,"val":112,"alg":113,"blk":114},
"cam12":{"dly":121,"val":122,"alg":123,"blk":124},
"cam13":{"dly":131,"val":132,"alg":133,"blk":134},
"cam14":{"dly":141,"val":142,"alg":143,"blk":144}
}
}
python2_7.py
import json
jscam=json.loads(json) #printing this also shows datas are unorderd
cam_js=jscam['cam']
for key,value in cam_js.iteritems():
print key
for key1,value1 in value.iteritems():
print key1,value1
print('\n')
输出
cam9
val 92
alg 93
blk 94
fl 91
cam8
val 82
alg 83
blk 84
fl 81
cam3
val 32
alg 33
blk 34
fl 31..............
它与原始json的顺序不一样,在我的情况下我需要以正确的顺序将其转换为html表, 谢谢
答案 0 :(得分:5)
Python dict是无序的,因此您会丢失初始数据的顺序。
解决方法是使用内置OrderedDict
模块中的collections
:
import json
import collections
ordered_json = json.loads(your_json_string, object_pairs_hook=collections.OrderedDict)
有关OrderedDict here的更多文档。