【问题标题】:How to Iterate through nested JSON in Python如何在 Python 中遍历嵌套的 JSON
【发布时间】:2020-04-09 14:11:39
【问题描述】:

我想了解如何在 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 行,在 打印(数据项['DataInfo']['lnames']) TypeError:列表索引必须是整数或切片,而不是 str [0.1s完成]

【问题讨论】:

  • 试试dataitems['DataInfo'][0]['lnames']),DataInfo是列表
  • 我知道你想要在 python 中,但在shell 你可以使用jq 作为cat given.json | jq -r ".datainfos[].DataInfo[].id"

标签: python json python-3.x nested iteration


【解决方案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'])

【讨论】:

  • 谢谢,您的第一个选项立即生效。多年来一直在为此苦苦挣扎。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:
      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

      【讨论】:

        猜你喜欢
        • 2022-01-01
        • 2016-12-27
        • 2019-11-11
        • 2017-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多