簡體   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