关于解析复杂多层json
1、输入json,输出为 key :value ,不支持value为列表情况,key为.连接的多层key
def dict_generator(indict, pre=None):
pre = pre[:] if pre else []
if isinstance(indict, dict):
for key, value in indict.items():
if isinstance(value, dict):
if len(value) == 0:
yield pre + [key, '{}']
else:
for d in dict_generator(value, pre + [key]):
yield d
elif isinstance(value, list):
if len(value) == 0:
yield pre + [key, '[]']
else:
for v in value:
for d in dict_generator(v, pre + [key]):
yield d
elif isinstance(value, tuple):
if len(value) == 0:
yield pre + [key, '()']
else:
for v in value:
for d in dict_generator(v, pre + [key]):
yield d
else:
yield pre + [key, value]
else:
yield indict
2、输入为json及需要的key,产出为key对应的所有value,添加至列表返回,可自定义
def print_keyvalue_by_key(input_json, key):
key_value = ""
if isinstance(input_json, dict):
for json_result in input_json.values():
if key in input_json.keys():
key_value = input_json.get(key)
else:
print_keyvalue_by_key(json_result, key)
elif isinstance(input_json, list):
for json_array in input_json:
print_keyvalue_by_key(json_array, key)
if key_value != "":
for value in key_value:
if "contents" == key:
s = value[:-1].lstrip("[")
json_loads = json.loads(s)
json_dumps = json.dumps(json_loads)
return json_dumps
else:
list_add.append(value)
return list_add
3、输入为json,同级的两个key,返回为统计的两个value
def get_all_field(data,key,params_key):
"""递归解析json
:param data: json数据
:return: key的值和params_key的值"""
if isinstance(data,dict):
for k, vin data.items():
if key == kand params_key in data:
yield v,data[params_key]
elif k !=params_key:
for a, bin get_all_field(v,key,params_key):
yield a, b
elif isinstance(data,list):
for v in data:
for a, b in get_all_field(v,key,params_key):
yield a, b
if __name__ =='__main__':
for a,b in get_all_field(json, filed,param):
print(a,b)