关于解析各种复杂json
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于解析各种复杂json相关的知识,希望对你有一定的参考价值。
参考技术A 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_dumps = json.dumps(json_loads)
return json_dumps
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)
以上是关于关于解析各种复杂json的主要内容,如果未能解决你的问题,请参考以下文章