解析嵌套JSON并在列表中收集数据

wnrlj8wa  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(91)

我正在尝试解析一个嵌套的JSON,并尝试在某种条件下将数据收集到一个列表中。
输入JSON如下:

[
    {
        "name": "Thomas",
        "place": "USA",  
        "items": [
            {"item_name":"This is a book shelf", "level":1},
            {"item_name":"Introduction", "level":1},
            {"item_name":"parts", "level":2},   
            {"item_name":"market place", "level":3},
            {"item_name":"books", "level":1},
            {"item_name":"pens", "level":1},
            {"item_name":"pencils", "level":1}
        ],
        "descriptions": [
            {"item_name": "Books"}  
        ]
    },
    {
        "name": "Samy",
        "place": "UK",  
        "items": [
            {"item_name":"This is a cat house", "level":1},
            {"item_name":"Introduction", "level":1},
            {"item_name":"dog house", "level":3},   
            {"item_name":"cat house", "level":1},
            {"item_name":"cat food", "level":2},
            {"item_name":"cat name", "level":1},
            {"item_name":"Samy", "level":2}
        ],
        "descriptions": [
            {"item_name": "cat"}    
        ]
    }

]
我阅读json如下:

with open('test.json', 'r', encoding='utf8') as fp:
    data = json.load(fp)
for i in data:
   if i['name'] == "Thomas":
      #collect "item_name", values in a list (my_list) if "level":1
      #my_list = []

预期产出:

my_list = ["This is a book shelf", "Introduction", "books", "pens", "pencils"]

因为这是一个嵌套的复杂JSON,我不能收集数据到一个列表中,我上面提到的。请让我知道没有如何收集数据从嵌套的JSON。

bf1o4zei

bf1o4zei1#

试试看:

import json

with open("test.json", "r", encoding="utf8") as fp:
    data = json.load(fp)

my_list = [
    i["item_name"]
    for d in data
    for i in d["items"]
    if d["name"] == "Thomas" and i["level"] == 1
]
print(my_list)

这将打印:

['This is a book shelf', 'Introduction', 'books', 'pens', 'pencils']

或者不理解列表:

my_list = []
for d in data:
    if d["name"] != "Thomas":
        continue
    for i in d["items"]:
        if i["level"] == 1:
            my_list.append(i["item_name"])

print(my_list)

相关问题