一、处理json文件的四个函数
函数 | 作用 |
---|---|
json.dumps | 对数据进行编码,将python中的字典 转换为 字符串 |
json.loads | 对数据进行解码,将字符串 转换为 python中的字典 |
json.dump | 将dict数据写入json文件中 |
json.load | 打开json文件,并把字符串转换为python的dict数据 |
二、dumps、loads案例
import json
tesdic = {
'name': 'Tom',
'age': 18,
'score':
{
'math': 98,
'chinese': 99
}
}
print(type(tesdic))
json_str = json.dumps(tesdic)
print(json_str)
print(type(json_str))
newdic = json.loads(json_str)
print(newdic)
print(type(newdic))
三、dump、load案例
写入json的内容只能是dict类型,字符串类型的将会导致写入格式问题
with open("res.json", 'w', encoding='utf-8') as fw:
json.dump(json_str, fw, indent=4, ensure_ascii=False)
with open("res.json", 'w', encoding='utf-8') as fw:
json.dump(tesdic, fw, indent=4, ensure_ascii=False)
with open("res.json", 'r', encoding='utf-8') as fw:
injson = json.load(fw)
print(injson)
print(type(injson))