首页 > 解决方案 > 如何在 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]

标签: pythonjsonpython-3.xnestediteration

解决方案


无论我从您的问题中了解到什么,您都需要该特定 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。如果你想将它存储在某个地方,那么将我们添加到该变量中。


推荐阅读