python解析数据格式的参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# -*- coding:utf-8 -*-
# Author: Lucy
 
"json的解析"
 
import json
# data = '{"a":"A","b":[2,4],"c":3.0}'  #json格式
#
# decoded = json.loads(data)
# print("DECODED:",decoded)
 
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
 
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
 
with open(r'E:\py_project\shuati\demo\1','r',encoding='utf8')as fp:
    data = json.load(fp)
 
ks = get_json_keys(data)
print(ks)
print("*************************")
print(get_key_values(data, ks))
 
dic = {}
 
def json_txt(dic_json):
    if isinstance(dic_json, dict):  # 判断是否是字典类型isinstance 返回True false
        for key in dic_json:
            if isinstance(dic_json[key], dict):  # 如果dic_json[key]依旧是字典类型
                print("****key--:%s value--: %s" % (key, dic_json[key]))
                json_txt(dic_json[key])
                dic[key] = dic_json[key]
            else:
                print("****key--:%s value--: %s" % (key, dic_json[key]))
                dic[key] = dic_json[key]
 
 
 
json_txt(data)
print("dic ---: " + str(dic))

  

posted @   四叶草134  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示