关于解析各种复杂json
发布网友
发布时间:2022-11-26 15:43
我来回答
共1个回答
热心网友
时间:2023-10-12 00:18
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
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_mps = json.mps(json_loads)
return json_mps
else:
list_add.append(value)
return list_add
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)