import json person = { "name":"zhangsan", "sex":"男", "age":20 } print(person) print(type(person)) print("-----------------") p1=json.dumps(person) #person将字典格式转化成字符串格式了 print(p1) print(type(p1)) print("-----------------") p2=json.loads(p1) #将字符串格式转换成字典格式 print(p2) print(type(p2)) with open('./p3.json','w',encoding='utf-8') as f: #在当前目录写入一个p3.json的文件 f.write(json.dumps(person,ensure_ascii=False,indent=4)) #输出结果不是以ASCii码=true输出 f.close() #关闭文件
执行后结果如下:
D:Pythonpython.exe E:/wj/LeetCode/wj_SaaS/wj/jsondumpsloads.py {'name': 'zhangsan', 'sex': '男', 'age': 20} <class 'dict'> ----------------- {"name": "zhangsan", "sex": "u7537", "age": 20} <class 'str'> ----------------- {'name': 'zhangsan', 'sex': '男', 'age': 20} <class 'dict'> Process finished with exit code 0
然后我保存写入的p3.json文件内容:
{ "name": "zhangsan", "sex": "男", "age": 20 }