我正在尝试解析一个嵌套的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。
1条答案
按热度按时间bf1o4zei1#
试试看:
这将打印:
或者不理解列表: