更新时间:2023-02-14 12:20:35
As mentioned in the comments, the not accepted answer in the linked question works perfectly fine for you case:
data = {
"results": [
{
"Fruit": "Apple",
"Nested fruit": [
"Orange"
],
"Title1": "Some text",
"Contents": {
"Name 1": [
"John Smith"
],
"Name 2": [
"Tyler"
],
"Name 3": [
"Bob",
"Rob"
],
"Name 4": [
"Linda"
],
"Name 5": [
"Mark",
"Matt"
],
"Some boolean": [
True
]
},
"More stuff": "More random text",
"Confusing": [
{
"Some info": "456",
"Info I want": "849456"
}
],
"Not important": [
{
"random text": "bla",
"random text2": "bla bla"
}
],
"Not important 2": "000",
"Not important3": [
"whatever",
"whatever"
],
"Not important 4": "16",
"Not important 5": "0058"
}
]
}
def item_generator(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 item_generator(v, lookup_key)
elif isinstance(json_input, list):
for item in json_input:
yield from item_generator(item, lookup_key)
res = item_generator(data, 'More stuff')
print([x for x in res])
res = item_generator(data, 'Info I want')
print([x for x in res])
输出:
['More random text']
['849456']