json是一种轻量级、跨平台、跨语言的数据交换格式; json模块提供了对json的支持,它既包含了将json字符串恢复成Python对象的函数,也提供了将Python对象转换成json字符串的函数
d1 = [{"id" : 1,"name" : "Number1","age" : 11},{"id" : 2,"name" : "Number2","age" : 22},{"id" : "3","name" : "Number3","age" : 33}]
d2 = {"persons" :[{"id" : 1,"name" : "Number1","age" : 11},{"id" : "2","name" : "Number2","age" : 22},{"id" : 3,"name" : "Number3","age" : 33}]}
d3 = {"code" : 200, "persons" :[{"id" : 1,"name" : "Number1","age" : 11},{"id" : True,"name" : "Number2","age" : 22},{"id" : 3,"name" : "Number3","age" : 33}]}
## 获取 json 数组或json 对象的 key 列表
def get_json_keys(json_str,json_keys = []):
if isinstance(json_str,list):
for json_obj in json_str:
for key in json_obj.keys():
if key not in json_keys:
json_keys.append(key)
elif isinstance(json_str,dict):
for key in json_str.keys():
if key not in json_keys:
json_keys.append(key)
return json_keys
## 将json 数组中相同的 key – value值进行合并
def get_key_values(json_str,json_keys):
target_json = {}
for key in json_keys:
key_values = []
for json_obj in json_str:
if isinstance(json_obj,dict):
key_values.append(json_obj[key])
target_json[key] = key_values
return target_json
## 主方法
def analyse_json(json_str):
target_json = {}
json_keys = []
if isinstance(json_str,list):
json_keys = get_json_keys(json_str,json_keys)
target_json = get_key_values(json_str,json_keys)
elif isinstance(json_str,dict):
json_keys = get_json_keys(json_str,json_keys)
for key in json_keys:
if not isinstance(json_str[key],list) and not isinstance(json_str[key],dict):
target_json[key] = json_str[key]
else:
target_json[key] = analyse_json(json_str[key])
return target_json
print(analyse_json(d1))
print(analyse_json(d2))
print(analyse_json(d3))
输出:
{'id': [1, 2, '3'], 'name': ['Number1', 'Number2', 'Number3'], 'age': [11, 22, 33]}
{'persons': {'id': [1, '2', 3], 'name': ['Number1', 'Number2', 'Number3'], 'age': [11, 22, 33]}}
{'code': 200, 'persons': {'id': [1, True, 3], 'name': ['Number1', 'Number2', 'Number3'], 'age': [11, 22, 33]}}
分享名称:使用Python对复杂的json进行解析
文章分享:http://www.shufengxianlan.com/qtweb/news3/468753.html
成都网站建设公司_创新互联,为您提供品牌网站制作、网站内链、网站导航、域名注册、服务器托管、手机网站建设
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联