[英]Python - read json file
I am trying to read the JSON file in python and it is successfully however some top values are skipped. 我正在尝试在python中读取JSON文件,并且成功,但是跳过了一些最高值。 I am trying to debug the reason. 我正在尝试调试原因。 Here is the the code. 这是代码。
data = json.load(open('pre.txt'))
for key,val in data['outputs'].items():
print key
print data['outputs'][key]['feat_left']
EDIT Here is the snapshot the file. 编辑这是文件的快照。 I want to read key
and feat_left
for outputs 我想读取key
和feat_left
作为输出
{
"outputs": {
"/home/113267806.jpg": {
"feat_left": [
2.369331121444702,
-1.1544183492660522
],
"feat_right": [
2.2432730197906494,
-0.896904468536377
]
},
"/home/115061965.jpg": {
"feat_left": [
1.8996189832687378,
-1.3713303804397583
],
"feat_right": [
1.908974051475525,
-1.4422794580459595
]
},
"/home/119306609.jpg": {
"feat_left": [
-0.7765399217605591,
-1.690917730331421
],
"feat_right": [
-1.1964678764343262,
-1.9359161853790283
]
}
}
}
PS: Thanks to Rahul KP for the code PS:感谢Rahul KP提供的代码
No top values are skipped. 没有最高值被跳过。 There are 45875 items in your data['output'] object. 您的data ['output']对象中有45875个项目。 Try the following code: 尝试以下代码:
len(data['outputs'].items())
And there are exactly 45875 items in your JSON file. JSON文件中恰好有45875个项目。 Just note that JSON object is an unordered collection in python, like dict
. 请注意,JSON对象是python中的无序集合,例如dict
。
i think you want: 我想你想要:
for key, val in data['outputs'].items():
if 'feat_left' in val:
print key, data['outputs'][key]['feat_left']
If you just want to print the content of the file by using a for-loop, you can try like this: 如果您只想使用for循环来打印文件的内容,则可以尝试如下操作:
data = json.load(open('pre.txt')
for key,val in data['outputs'].items():
print key
print val[0] #this will print the array and its values below "feat_left", if the json is consistent
A more robust solution could look like this: 一个更强大的解决方案可能看起来像这样:
data = json.load(open('pre.txt')
for key,val in data['outputs'].items():
print key
for feat_key, feat_val in val.items():
if feat_key == 'feat_left':
print feat_val
Code is untested, give it a try. 代码未经测试,请尝试一下。
Try this: 尝试这个:
for key, val in data['outputs'].items():
print key, val['feat_left']
#output /home/119306609.jpg [-0.7765399217605591, -1.690917730331421]
This get every key and element within 'feat_left' Then you can display in the page however you like 这将获取'feat_left'中的所有键和元素,然后您可以根据需要在页面中显示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.