如果匹配元素,则获取特定的 Json 数组

时间:2021-04-22 16:12:34

标签: python json python-3.x

我有以下 JSON 数组。如果device['name'] = 'DJ',那么我想检索从event_locationsum_text的整个json数组,否则我不想要那个数组。

{
  "results": [
    {
      "event_location": "San Jose",
      "event_type": "Party",
      "source_type": [
        "COMPANY",
        "CONSUM"
      ],
      "device": [
        {
          "name": "DJ",
          "date_order": "20210120",
          "manufacturer_country": "USA"
        }
      ],
      "problems": [
        "Material Rupture"
      ],
      "zip_code": "",
      "sum_text": [
        {
          "sum_text_key": "220229361",
          "text_type_code": "Additional Manufacturer Narrative",
          "text": "A REVIEW OF THE DEVICE HISTORY RECORD HAS BEEN INITIATED."
        },
        {
          "sum_text_key": "220229362",
          "text_type_code": "Description of Event or Problem",
          "text": "DEVICE REPORTED RIGHT SIDE RUPTURE."
        }
      ]
    },
    {
      "event_location": "New York",
      "event_type": "Baby Shower",
      "source_type": [
        "COMPANY",
        "CONSUM"
      ],
      "device": [
        {
          "name": "Musical Band",
          "date_order": "20210120",
          "manufacturer_country": "USA"
        }
      ],
      "problems": [
        "Material Rupture"
      ],
      "zip_code": "",
      "sum_text": [
        {
          "sum_text_key": "220229361",
          "text_type_code": "Additional Manufacturer Narrative",
          "text": "A REVIEW OF THE DEVICE HISTORY RECORD HAS BEEN INITIATED."
        },
        {
          "sum_text_key": "220229362",
          "text_type_code": "Description of Event or Problem",
          "text": "DEVICE REPORTED RIGHT SIDE RUPTURE."
        }
      ]
    },
    {
      "event_location": "Boston",
      "event_type": "Wedding",
      "source_type": [
        "COMPANY",
        "CONSUM"
      ],
      "device": [
        {
          "name": "Soft Music Band",
          "date_order": "20210120",
          "manufacturer_country": "USA"
        }
      ],
      "problems": [
        "Material Rupture"
      ],
      "zip_code": "",
      "sum_text": [
        {
          "sum_text_key": "220229361",
          "text_type_code": "Additional Manufacturer Narrative",
          "text": "A REVIEW OF THE DEVICE HISTORY RECORD HAS BEEN INITIATED."
        },
        {
          "sum_text_key": "220229362",
          "text_type_code": "Description of Event or Problem",
          "text": "DEVICE REPORTED RIGHT SIDE RUPTURE."
        }
      ]
    }
  ]
}

我如何迭代它以便我只得到那个特定的数组。试图用 for 循环迭代它。但未能检索到整个数组。

1 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

json = {...data here}

for event in json['results']:
    for device in event['device']:
        if device["name"] == "DJ":
            print(event)

在行 print(event) 中,您可以对当前事件执行任何操作,将其附加到列表中,返回它,或执行任何您需要的操作。

另外,请注意 device 是 list 而不是 dict,因此我们遍历所有设备以查看其中一个是否与指定名称匹配。