[英]How to Iterate through nested JSON in Python
I would like to find out how I can iterate through the Following JSON in Python 3 Specifically I would like to be able to pull out 'id' and 'lname'.我想知道如何在 Python 3 中遍历以下 JSON 具体来说,我希望能够提取“id”和“lname”。 My actual JSON file has about 300 entries
我的实际 JSON 文件有大约 300 个条目
{
"datainfos": [{
"DataInfo": [{
"id": 1,
"lname": "Altitude",
"max": 62.79999923706055,
"min": -37.20000076293945,
"numInstances": 1,
"sname": "ALT",
"unit": "m"
}]
},
{
"DataInfo": []
},
{
"DataInfo": [{
"id": 3,
"lname": "Position Error",
"max": 0,
"min": 0,
"numInstances": 1,
"sname": "EPE",
"unit": "m"
}]
},
{
"DataInfo": [{
"id": 4,
"lname": "HDOP",
"max": 0,
"min": 0,
"numInstances": 1,
"sname": "HDOP",
"unit": ""
}]
}
]
}
My code is as below:我的代码如下:
import json
f = open('data1.json')
data = json.load(f)
f.close()
for dataitems in data['datainfos']:
print (dataitems['DataInfo'])
Python returns a list, not a dictionary. Python 返回一个列表,而不是一个字典。 When I try to use the following code
当我尝试使用以下代码时
import json
f = open('data1.json')
data = json.load(f)
f.close()
for dataitems in data['datainfos']:
print (dataitems['DataInfo']['lnames'])
I get the error:我收到错误:
Traceback (most recent call last): File "C:\\Users\\phil\\Documents\\Python Scripts\\UMP-VDR\\Testing Files\\convertjson.py", line 9, in print (dataitems['DataInfo']['lnames']) TypeError: list indices must be integers or slices, not str [Finished in 0.1s]
回溯(最近一次调用):文件“C:\\Users\\phil\\Documents\\Python Scripts\\UMP-VDR\\Testing Files\\convertjson.py”,第 9 行,打印中(dataitems['DataInfo']['lnames' ]) 类型错误:列表索引必须是整数或切片,而不是 str [在 0.1 秒内完成]
Use this code because your DataInfo is array.使用此代码是因为您的 DataInfo 是数组。
import json
f = open('data1.json')
data = json.load(f)
f.close()
for dataitems in data['datainfos']:
for datainfo in dataitems['DataInfo']:
print(datainfo['id'], datainfo['lname'])
Or change your json file like this:或者像这样更改您的 json 文件:
{
"datainfos": [
{
"DataInfo":
{
"id": 1,
"lname": "Altitude",
"max": 62.79999923706055,
"min": -37.20000076293945,
"numInstances": 1,
"sname": "ALT",
"unit": "m"
}
},
{
"DataInfo": {}
},
{
"DataInfo":
{
"id": 3,
"lname": "Position Error",
"max": 0,
"min": 0,
"numInstances": 1,
"sname": "EPE",
"unit": "m"
}
},
{
"DataInfo":
{
"id": 4,
"lname": "HDOP",
"max": 0,
"min": 0,
"numInstances": 1,
"sname": "HDOP",
"unit": ""
}
}
]
}
And change your code like this:并像这样更改您的代码:
import json
f = open('asd.json')
data = json.load(f)
f.close()
for dataitems in data['datainfos']:
if(dataitems['DataInfo']):
print(dataitems['DataInfo']['id'], dataitems['DataInfo']['lname'])
Iterating over a dictionary in python will return the keys by default.默认情况下,在 python 中迭代字典将返回键。 You probably want
.items()
.你可能想要
.items()
。 But in this case you probably want:但在这种情况下,您可能想要:
import json
data = json.load(open('file.json'))
out = []
for x in data['datainfos']:
if x['DataInfo']:
out.append((x['DataInfo'][0]['id'], x['DataInfo'][0]['lname']))
print(out)
>>> [(1, 'Altitude'), (3, 'Position Error'), (4, 'HDOP')]
Whatever i understand from your question is that you want id and lname for that particular id.我从您的问题中了解到的是,您需要该特定 ID 的 id 和 lname。 So to do that in simple way with n^2 complexity is as below:
因此,要以简单的方式以 n^2 的复杂度执行此操作,如下所示:
import json
f = open('data.json')
data = json.load(f)
f.close()
for dataitems in data['datainfos']:
for DataInfo in dataitems['DataInfo']:
print(DataInfo['id'],DataInfo['lname'])
This will give you the particular id with lname.这将为您提供带有 lname 的特定 ID。 And if you want to store it somewhere then add us to that variable.
如果你想将它存储在某个地方,那么将我们添加到该变量中。
for x in range(0,len(sample_dict.get('datainfos'))):
if len(sample_dict.get('datainfos')[x]['DataInfo'])==0:
print('Empty list')
else:
print('ID IS {}, NAME IS {}'.format(sample_dict.get('datainfos')[x]['DataInfo'][0]['id'],sample_dict.get('datainfos')[x]['DataInfo'][0]['lname']))
This will iterate and print id and names.这将迭代并打印 id 和名称。 Will print empty for no name & ID.
如果没有姓名和 ID,将打印为空。 Your json is stored as sample_dict
您的 json 存储为 sample_dict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.