读取json文件
import json
path = "a.json" # path为路径或者文件
with open(path,encoding="utf-8") as op:
contents = json.load(op)
保存在json文件
import json
path = "a.json"
dict = {"name": "张三", "age": 18, "sex": "男"}
with open(path,"a",encoding="utf-8") as op:
json.dump(dict,op,ensure_ascii=False)
转换json格式为字典格式
import json
js = '{"name": "张三", "age": 18, "sex": "男"}'
dic = json.loads(js,encoding="utf-8")
print(dic)
控制台输出
{'name': '张三', 'age': 18, 'sex': '男'}
将字典格式转换为json格式
import json
dict1 = {'name': '张三', 'age': 18, 'sex': '男'}
js1 = json.dumps(dict1,ensure_ascii=False)
print(js1)
控制台输出
{"name": "张三", "age": 18, "sex": "男"}