您必须递归搜索 JSON 对象才能找到所需的密钥。代码搜索所有级别以找到匹配的键。以下代码改编自Stack answer。
def get_values(json_input, lookup_key):
if isinstance(json_input, dict):
for k, v in json_input.items():
if k == lookup_key:
yield v
else:
yield from get_values(v, lookup_key)
elif isinstance(json_input, list):
for item in json_input:
yield from get_values(item, lookup_key)
例如,
dict_test = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
print(list(get_values(dict_test, "id")))
输出:
['0001',
'1001',
'1002',
'1003',
'1004',
'5001',
'5002',
'5005',
'5007',
'5006',
'5003',
'5004']
上面的输出显示了 所有级别中键 id 的匹配值。