一、参考链接
https://docs.python.org/zh-cn/3/library/json.html
二、python类型转换成json
1、
def test_to_json(self):
'''
python字典类型转换为str格式的json
:return:
'''
request = {
'url': 'www.XX.com',
'params': {
'username': 'xian',
'password': 'test1234'
}
}
print(type(json.dumps((request))),json.dumps(request))
2、
def test_write_file(self):
'''
python类型转换为json并写入文件
:return:
'''
request={
'url':'www.XX.com',
'params':{
'username':'xian',
'password':'test1234'
}
}
with open('./data.json','w',encoding='utf-8') as f:
json.dump(request,f)
三、json转换成python类型
1、
def test_to_dict(self):
'''
json转化为dict
:return:
'''
my_json='{"url": "www.XX.com", "params": {"username": "xian", "password": "test1234"}}'
print(json.loads(my_json))
2、
def test_jsonfile_to_dict(self):
'''
加载json文件,转换为python类型
:return:
'''
my_dict={}
with open('./data.json','r',encoding='utf-8') as f:
my_dict=json.load(f)
print(my_dict)