python - 如何在 Python 中遍历嵌套的 JSON
问题描述
我想了解如何在 Python 3 中遍历以下 JSON,具体来说,我希望能够提取“id”和“lname”。我的实际 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": ""
}]
}
]
}
我的代码如下:
import json
f = open('data1.json')
data = json.load(f)
f.close()
for dataitems in data['datainfos']:
print (dataitems['DataInfo'])
Python 返回一个列表,而不是字典。当我尝试使用以下代码时
import json
f = open('data1.json')
data = json.load(f)
f.close()
for dataitems in data['datainfos']:
print (dataitems['DataInfo']['lnames'])
我得到错误:
Traceback(最近一次调用最后一次):文件“C:\Users\phil\Documents\Python Scripts\UMP-VDR\Testing Files\convertjson.py”,第 9 行,打印中(dataitems['DataInfo']['lnames' ]) TypeError: list indices must be integers or slices, not str [Finished in 0.1s]
解决方案
无论我从您的问题中了解到什么,您都需要该特定 id 的 id 和 lname 。因此,以 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'])
这将为您提供带有 lname 的特定 ID。如果你想将它存储在某个地方,那么将我们添加到该变量中。
推荐阅读
- python - 为什么我不能正确预测 1 行数据?
- arduino -
循环迭代后串行监视器自动输入 0 - javascript - 如何在本机反应中过滤数组中的元素
- laravel - Laravel 种子的问题
- python - 无需先读取整个文件即可读取 GeoTIFF 文件的子集/子区域?
- terraform - local-exec DESTROY 供应商中的 terraform 和引用
- r - 通过 R Studio 中的控制台通过相对路径访问文件有效,但不在 Markdown 文档中
- postman - Postman 模拟示例响应 json 数据以包含 pathParms 或 queryParms 或放置 body json 对象
- javascript - Redux 选择器 - 使用选择器过滤然后排序
- python - 在 Win 10 上安装 Kivy 的问题