json.dumps() 和 json.loads()的区别
一、两者区别
json.dumps() 用于将字典转换为字符串格式
son.loads() 用于将字符串转换为字典格式
import json diction ={ "name":"aa", "phonenumber":13305958697865, "grade":"3class"} print(diction) #原文件格式为字典 d1 = json.dumps(diction)#将字典转换为字符串 print(d1) d2 = json.loads(d1)#将字符串转换为字典 print(d2) print('d',type(diction)) print('d1',type(d1)) print('d2',type(d2))
输出结果:
{'phonenumber': 13305958697865, 'grade': '3class', 'name': 'aa'} {"phonenumber": 13305958697865, "grade": "3class", "name": "aa"} {'phonenumber': 13305958697865, 'grade': '3class', 'name': 'aa'} d <class 'dict'> d1 <class 'str'> d2 <class 'dict'>
二、注意事项
将dict类型数据写入json 文件时会报错,需要先将dict类型转换为字符串格式再写入json文件中。则需用到json.dumps()
with open('d3.json','w',encoding='utf-8') as f: f.write(json.dumps(diction))#将dict同过json.dumps()转换为字符串写入json文件 f.close()
查看d3.json文件内容:
{"phonenumber": 13305958697865, "name": "aa", "grade": "3class"}