python之json字典基础处理

 

 1、json解析基础操作

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
json.dumps()和json.loads()是json格式处理函数(json.dumps()是把字典类型格式化json对象,json.loads()把json对象转成字典)
json.dump()和json.load()是json文件处理(json.load()用于读取文件,json.dump()用于写文件)
'''

import json
#———————————把字典转成json字符串——————————————
dic1 = {'type':'dic1','username':'loleina','age':16,'chen':'湖北省广水市关庙镇','所属国家':'宇宙安全局'}
#json_dic1 = json.dumps(dic1)#不能打印中文(json.dumps默认是ascii码)
json_dic1=json.dumps(dic1, ensure_ascii=False)#可打印中文
print (json_dic1)

#——————————字典格式化_显示json对象数据格式——————————————————
json_dic2 = json.dumps(dic1,sort_keys=True,indent =4,separators=(',', ': '),ensure_ascii=False)#ensure_ascii表示是否使用asciii编码
print (json_dic2)

#————————把json对象格式写入文件(保存格式为json字符串)————————————————
with open('casedate.json', 'w', encoding='utf-8') as f:#写文件
  json.dump(json_dic2, f, sort_keys=True, ensure_ascii=False,indent=4)#ensure_ascii表示编码

#——————————把字典写入到文件(保存为json对象格式)———————————————————————
chenchen = {'type':'dic1','username':'loleina','age':16,'chen':'湖北省广水市关庙镇','所属国家':'宇宙安全局'}
with open('chenwei.json', 'w', encoding='utf-8') as f:#写文件
  json.dump(chenchen, f, sort_keys=True, ensure_ascii=False,indent=4)#ensure_ascii表示编码

#————————————把json字符串转成字典__然后再转成json对象格式—————————————————
aa="{\n    \"age\": 16,\n    \"chen\": \"湖北省广水市关庙镇\",\n    \"type\": \"dic1\",\n    \"username\": \"loleina\",\n    \"所属国家\": \"宇宙安全局\"\n}"
bb=json.loads(aa)#转为字典格式
print(bb)
#转成json对象格式
cc = json.dumps(bb,sort_keys=True,indent =4,separators=(',', ': '),ensure_ascii=False)#ensure_ascii表示是否使用asciii编码
print(cc)
#-----------------------------从文件中读取数据------------------------------------------------------
#第一种方法,从文件读取json数据
file = open('chenwei.json','r',encoding='utf-8')
info = json.load(file)#直接读取文件,不需要file.read()
print(info)

#第二种方法(写完文件自动关闭)    
with open('chenwei.json','r', encoding='utf-8') as f:
    cc=f.read()
k=json.loads(cc)#把json格式转为字典
print(k)

 

2、格式转换

#________________________________________________________json字符串格式化为json格式____________________________________________________
cc={"nodeResult": "进服成功", "work_flow_type": 2, "time": 1601455509, "sign": "132e916ede1455ceac0cea0b6cdb04cf", "job_flow_id": 20910, "nodeStatus": 1, "nodeName": "进服", "pkgId": 3344}
json_dict_2 = json.dumps(cc, indent=2, sort_keys=True, ensure_ascii=False)
print(json_dict_2)


#________________________________________________________把json字符串_转成字典___________________________________________________________
nn={"work_flow_type": 2, "pkgId": 3344, "time": 1601455509, "nodeName": "进服", "nodeStatus": 1, "nodeResult": "进服成功", "job_flow_id": 20910, "sign": "132e916ede1455ceac0cea0b6cdb04cf"}
cc=repr(str(nn))#把nn转成str,然后左右两把加引号
print(cc)
print(json.loads(cc))#转为字典格式


#____________________________________________str转dict_________________________________________________________________________________
user_info = "{'name' : 'john', 'gender' : 'male', 'age': 28}"
user_dict = json.loads(user_info)#直接转会报错(由于 json 语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号),,可以用repr函数即可
#user_dict = json.loads(repr(user_info))


import ast
user = '{"name" : "john", "gender" : "male", "age": 28}'
user_dict = ast.literal_eval(user)
#使用 ast.literal_eval 进行转换既不存在使用 json 进行转换的问题,也不存在使用 eval 进行转换的 安全性问题,因此推荐使用 ast.literal_eval


备注三种转换方式(https://www.cnblogs.com/xiao-xue-di/p/11414210.html)
#_______________________把带true或者flase的json数据 转成dict__________________________________
'''注意直接放在变量会报错,需要通过多行格式化注释(使用json.loads可以将json序列化成dcit,可以自动把true、false、null转换)'''
bb="""{
  "job_flow_id": 20910,
  "nodeName": "进服",
  "nodeResult": "进服成功",
  "nodeStatus": true,
  "pkgId": 3344,
  "sign": "132e9166cdb04cf",
  "time": 1601455509,
  "work_flow_type": 2
}
"""
print(json.loads(bb))
import json #__________________________________________________字典内嵌套json,并把字典转成json格式__________________________________________________________ aa={'nodeResult': '下单调起微信成功', 'nodeArgs': '{"system_version": "9", "model": "MHA-AL00", "network": "当前网络为-wifi", "imei": "A000007A5A20BD"}', 'nodeName': '下单调起微信', 'nodeStartTime': 1604573095, 'nodeStatus': 1, 'sign': '15631c56b61d633d3f705221f9218093'} print(type(aa)) aa["nodeArgs"]=json.loads(aa["nodeArgs"])#把json对象转成dict json_dic1=json.dumps(aa, ensure_ascii=False)#可打印中文 print(json_dic1)

 

 3、处理带斜杠的字典

#__________________________________________________________________________________________________带false的字典互转____________________________________________________________________________
#字典只支持False的大写,json支持小写,,字典转到字符串自动变小写,字符串转到字典自动变大写
aa={'msgtype': 'markdown', 'markdown': {'title': '小麻雀接口报警', 'text': '#### {\'任务名称\': \'dsdk_接口1\', \'用例总数\': 1, \'成功用例\': 0, \'未执行\': 0, \'失败用例\': 1},失败用例信息如下: \n>  【第1个】[判断是否有公告1](http://x.x.x.x:8001/case_manage/?caseid=4) \n> #### 预期结果:or="22success22" \n> #### 匹配结果:<font color=#FF0000>失败</font> \n>  #### 响应信息:{"ret":1,"content":"","msg":"success"} \n\n>  \n'}, 'at': {'atMobiles': [], 'isAtAll': False}}
# print(type(aa))#字典类型
# print(aa)

# #字典序列化成str
aa1=json.dumps(aa, ensure_ascii=False)#可打印中文
print(type(aa1))
print(aa1)

#字符串转成dict
aa2=json.loads(aa1)
print(type(aa2))
print(aa2)



###_________________________________________________字典转json格式___________________________________________________________________________________________________________________________________
bb={
    'msgtype': 'markdown',
    'markdown': {
        'title': '小麻雀接口报警',
        'text': '#### {\'任务名称\': \'dsdk_接口1\', \'用例总数\': 1, \'成功用例\': 0, \'未执行\': 0, \'失败用例\': 1},失败用例信息如下: \n>  【第1个】[判断是否有公告1](http://x.x.x.x:8001/case_manage/?caseid=4) \n> #### 预期结果:or="22success22" \n> #### 匹配结果:<font color=#FF0000>失败</font>,httpCode:<font color=#32CD32>200</font> \n> #### [https://game.wbdd2018.com/v1/game/sdk/bulletin](https://game.wbdd2018.com/v1/game/sdk/bulletin) \n> #### 响应信息:{"ret":1,"content":"","msg":"success"} \n\n>  \n'
    },
    'at': {
        'atMobiles': [],
        'isAtAll': False
    }
}

##方式一
cc=json_dic1=json.dumps(bb, ensure_ascii=False)#可打印中文
print(cc)

##方式二
# msg = json.JSONEncoder().encode(bb)
# print(msg)


#_______________________________________________从网上接口返回json的false小写,,字典不支持__________________________________________________________________________________________
false=False
cc={"msgtype": "markdown", "markdown": {"title": "\u5c0f\u9ebb\u96c0\u63a5\u53e3\u62a5\u8b66", "text": "#### {'\u4efb\u52a1\u540d\u79f0': 'dsdk_\u63a5\u53e31', '\u7528\u4f8b\u603b\u6570': 1, '\u6210\u529f\u7528\u4f8b': 0, '\u672a\u6267\u884c': 0, '\u5931\u8d25\u7528\u4f8b': 1}\n"}, "at": {"atMobiles": [], "isAtAll": false}}
print(cc)

 

4、字典拆分:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
#——————————————————————————————————字典嵌套——————————————————————————————————————————
a={'t_hope': '{code:1,msg:登陆成功}', 't_method': 'post', 't_id': '1001'}
b={"info": [{"t_id": "1002", "t_name": "商品列表", "t_method": "get", "t_url": "http://XXX?getFoodList", "t_param": "{}",
                  "t_hope": "{code:1,msg:成功,info:[{name:123,detal:dfadfa,img:product/1.png}]}", "t_actual": "{code:1,msg:成功,info:[{name:123,detal:dfadfa,img:product/1.png},{name:456,detal:dfadfa,img:product/1.png}]}", "t_result": "成功"}],
        "test_sum": 100,"test_success": 20, "test_failed": 80}
print(a['t_hope'])
print(type(b))
##把字典中key或value提取出来
# a=':'.join(b.keys()) #访问字典中的key(把keys替换成values则是提取值)
# keys_list=a.split(':')#把key组成为一个list
# print(keys_list)

#————————————————————————————字典嵌套2-拆分----------------------------------------------------------------------------------------------------
data = {"info": [{"t_id": "1001", "t_name": "登陆", "t_method": "post", "t_url": "http://XXX?login", "t_param": "{user_name:test,pwd:111111}",
                  "t_hope": "{code:1,msg:登陆成功}", "t_actual": "{code:0,msg:密码错误}", "t_result": "失败"}, {"t_id": "1002", "t_name": "商品列表", "t_method": "get", "t_url": "http://XXX?getFoodList", "t_param": "{}",
                  "t_hope": "{code:1,msg:成功,info:[{name:123,detal:dfadfa,img:product/1.png},{name:456,detal:dfadfa,img:product/1.png}]}", "t_actual": "{code:1,msg:成功,info:[{name:123,detal:dfadfa,img:product/1.png},{name:456,detal:dfadfa,img:product/1.png}]}", "t_result": "成功"}],
        "test_sum": 100,"test_success": 20, "test_failed": 80}

#字典值或建转list
a=':'.join(b.keys()) #访问字典中的key(把keys替换成values则是提取值)
print(a.split(':'))#打印所有的key
#遍历字典中嵌套字典(---抽离拆分子字典)
for i in (data['info']):
    print(i,'\n')
    #print(i["t_id"])#打印拆分后字典的key的值
print('-------------------------————————————————————————--')

#————————————————————————————将列表中的多个字典 合成一个成字典——————————————————————————————————————————
d1 = {}
l1 = ['{"xvda": {"I/O": {"r/s": "0.33", "await": "12.58", "w/s": "0.46"}, "use_%": "32", "total_G": "15G"}}', '{"xvdf": {"I/O": {"r/s": "0.00", "await": "20.23", "w/s": "0.01"}, "use_%": "2", "total_G": "100G"}}', '{"xvdg": {"I/O": {"r/s": "0.02", "await": "262.89", "w/s": "3.22"}, "use_%": "64", "total_G": "150G"}}']
#遍历列表中字典
for i in l1:
    print(i)#打印每个字典
    d1.update(json.loads(i))#把遍历的字典追加到d1字典
print(d1)

#_________________________________将一个字典内的value包含字典分解 (或叫提取)————————————————————————————————————————————
aa={'xvdf': {'use_%': '2', 'total_G': '100G', 'I/O': {'await': '20.23', 'w/s': '0.01', 'r/s': '0.00'}}}
#分解或遍历aa['xvdf']下的value
for key,value in aa['xvdf'].items():
    print({key:value})


#--------------------------------------------------------------两个列表转字典(list转字典)-------------------------------------------------------------------------
a=['项目', '模块', '用例id', '用例描述', '请求url', '请求方式', '请求数据', '预期结果', '实际返回', '测试结果', '测试人员']
b=['阿里云', '自己test', 'login_3', '正常登录', 'http://sso.newtest1.51dinghuo.cc/api/loginpost', 'POST', 'username=missy&password=8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92', '{"code":200,"desc":"登录成功!,但没有返回地址,故不跳转"}', '{"code":200,"desc":"登录成功!,但没有返回地址,故不跳转"}', '成功', 'chenwei']
dic3 = dict(zip(a, b))
print(dic3)
#——————————————————————把一个字典拆分成一个list(或两个list)--------------------------------------------------------
d={1:"a",2:"b",3:"c"}
result=[]
for k,v in d.items():
    result.append(k)
    result.append(v)#若拆分成两个list只需分开追加
print(result)
#-----------------------------------——————--两个字典合并——————————————————————————————————————
dd={1:"a",2:"b",3:"c"}
ee={'chen':'eeeeee'}
wei=dict(dd, **ee)
print(wei)

#——————————————————————把一个字典遍历根据键值__拆分多个字典————————————————————————————————
# arr = {'a': '苹果', 'b': '三星', 'c': '华为', 'd': '谷歌'}
dd={'xvdg': {'total_G': '150G', 'I/O': {'r/s': '0.02', 'await': '262.89', 'w/s': '3.22'}, 'use_%': '64'}, 'xvdf': {'total_G': '100G', 'I/O': {'r/s': '0.00', 'await': '20.23', 'w/s': '0.01'}, 'use_%': '2'}, 'xvda': {'total_G': '15G', 'I/O': {'r/s': '0.33', 'await': '12.58', 'w/s': '0.46'}, 'use_%': '32'}}
# 第一种
for (key,value) in dd.items():
    print({key:value})

#————————————————A字典里嵌套list然后,添加B字典到A字典的list里面————————————————————————————
chen={"info": [], "test_sum": 100,"test_success": 20, "test_failed": 80}
wei={'t_result': '失败', 't_url': 'http://XXX?login', 't_name': '登陆', 't_param': '{user_name:test,pwd:111111}', 't_method': 'post', 't_actual': '{code:0,msg:密码错误}', 't_hope': '{code:1,msg:登陆成功}', 't_id': '1001'}
ww={'t_param': '{}', 't_method': 'get', 't_actual': '{code:1,msg:成功,info:[{name:123,detal:dfadfa,img:product/1.png},{name:456,detal:dfadfa,img:product/1.png}]}', 't_hope': '{code:1,msg:成功,info:[{name:123,detal:dfadfa,img:product/1.png},{name:456,detal:dfadfa,img:product/1.png}]}', 't_name': '商品列表', 't_result': '成功', 't_id': '1002', 't_url': 'http://XXX?getFoodList'}
#把字典追加到list
chen["info"].append(wei)
chen["info"].append(ww)
print(chen)

 

5、json和字符串转义:

##################把转义字符串转成字典、再序列化成json格式############
import json
data = "{\"advertiser_id\":\"ADVERTISER_ID\",\"filtering\":{\"ids\":\"IDS\",\"ad_name\":\"AD_NAME\",\"status\":\"STATUS\",\"marketing_goal\":\"MARKETING_GOAL\"},\"page\":\"PAGE\",\"page_size\":\"PAGE_SIZE\"}"
###转字典
json_data = json.loads(data)
print(type(json_data))
###转json格式
json_str=json.dumps(json_data)
print(type(json_str))
print(json_str)

###############把json字符串加转义############################### import json data = {"name": "John", "age": 30, "city": "New York"} #字典类型格式化json对象 json_string = json.dumps(data) #在“号前加转义\ escaped_string = json_string.replace('"', '\\"') print(escaped_string) ###############把json字符串加转义############################### import json my_dict = {"type":"message","mid":3,"req":1,"uri":"v1/login","__uid_4_track":0,"td-op-uid":0,"data":{"ver":2,"client":{"source":"web","platform":"Windows","osUserName":"","userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36","signature":"3055941eada5990ec7a622764b2b3351","fingerprint":"41fd0e0753f57a64d10805a1d4e9f701"},"userName":"chanyantest-qy@sunteng.com","parentId":0,"pass":"09b47d2b85464fa530c73855109fd00f","salt":"0.9008329630359269","domain":"td.smallfighter.com","sCaptcha":"","gCaptcha":"","loginType":"email"}} my_str = json.dumps(my_dict).replace('"', '\\"') print(my_str)

 

 6、json和jsonp讲解

###什么是JSON:    JSON是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。它基于JavaScript的对象字面量表示法,广泛用于Web应用程序中数据传输。
###什么是JSONP:   JSONP是一种通过<script>标签请求数据的技术,通常用于解决跨域请求问题。它将JSON数据包装在一个函数调用中,从而让浏览器执行该函数并处理返回的数据。
### JSONP(JSON with Padding)是一种在JSON格式的基础上添加一层函数调用包裹的数据传输方式。它允许你在不同的域之间进行数据传输,通常用于绕过浏览器的同源策略限制,实现跨域请求。 ##json示例: { "name": "Alice", "age": 30, "is_student": false, "courses": ["Math", "Science"] } ##jsonp示例: callbackFunction({ "name": "Alice", "age": 30, "is_student": false })
#在Python中处理JSONP数据 import json import re
# 示例JSONP响应 jsonp_response = 'callbackFunction({"name": "Alice", "age": 30, "is_student": false});' # 使用正则表达式提取JSON部分 match = re.search(r'^\w+\((.*)\);$', jsonp_response) if match: json_data = match.group(1) data = json.loads(json_data) print(data) # 输出: {'name': 'Alice', 'age': 30, 'is_student': False}
#把json格式转成jsonp格式 import json data = { "query_content": "你是谁", "k": 8, "rerank": False, "score_threshold": 0.84, "qa_score_threshold": 0.83, "rerank_score_threshold": 0.06, "qa_rerank_score_threshold": 0.12, "global_search": True } # 指定回调函数名 callback_function = "myCallbackFunction" # 将数据转换为JSON字符串 json_data = json.dumps(data) # 创建JSONP格式的字符串 jsonp_data = f"{callback_function}({json_data});" print(jsonp_data)

 

相关连接:

https://blog.csdn.net/qq_31274209/article/details/80861356 ....................................................Python嵌套字典的一种赋值方式

https://blog.csdn.net/qq_66726657/article/details/143079749 .................................................python对json和jsonp介绍及处理

posted on 2019-05-17 16:34  chen_2987  阅读(339)  评论(0编辑  收藏  举报

导航