繁体   English   中英

如何在 Python 中遍历嵌套的 JSON

[英]How to Iterate through nested JSON in Python

我想知道如何在 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'])

我收到错误:

回溯(最近一次调用):文件“C:\\Users\\phil\\Documents\\Python Scripts\\UMP-VDR\\Testing Files\\convertjson.py”,第 9 行,打印中(dataitems['DataInfo']['lnames' ]) 类型错误:列表索引必须是整数或切片,而不是 str [在 0.1 秒内完成]

使用此代码是因为您的 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'])

或者像这样更改您的 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": ""
                }

        }
    ]
}

并像这样更改您的代码:

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'])

默认情况下,在 python 中迭代字典将返回键。 你可能想要.items() 但在这种情况下,您可能想要:

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')]

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

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']))

这将迭代并打印 id 和名称。 如果没有姓名和 ID,将打印为空。 您的 json 存储为 sample_dict

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM