Python提取目标Json键值:包含子嵌套列表和字典
目标:取json中所有的Name、Age字典
思路:递归处理字典中直接包含子字典的情况,
import json
def find_targ_dicts(data,key1,key2):
result = {}
if isinstance(data, dict):
if key1 in data and key2 in data: # 第一层字典中包含key1和key2
result[key1] = data[key1]
result[key2] = data[key2]
yield result
for k, v in data.items():
yield from find_targ_dicts(v, key1, key2) # 递归处理子字典
elif isinstance(data, list):
for item in data:
yield from find_targ_dicts(item, key1, key2)
# 示例JSON数据
json_data = '''
{
"name": "mkdm",
"age": 30,
"children": [
{
"name": "Ace",
"age": 10
},
{
"name": "Bob",
"age": 8
},
{
"tt":{"name": "coh",
"age": 9}
}
],
"address": {
"city": "shbj",
"addr": "sccd"
}
}
'''
# 将JSON字符串转换为Python对象
data = json.loads(json_data)
# 提取所有的字典
dicts = list(find_targ_dicts(data,'name','age'))
print(dicts)
# 打印所有的字典
for d in dicts:
print(d)
结果截图: