在python中对json的使用无非就是以下几种:

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))
输出为:
{"name": "Tom", "age": 18, "score": {"math": 98, "chinese": 99}}
{'name': 'Tom', 'age': 18, 'score': {'math': 98, 'chinese': 99}}
dict写为json文件:
with open("res.json", 'w', encoding='utf-8') as fw:
json.dump(tesdic, fw, indent=4, ensure_ascii=False)
json文件读为dict:
with open("res.json", 'r', encoding='utf-8') as fw:
injson = json.load(fw)
print(injson)
print(type(injson))
需要注意的是,写入的时候,必须是dict形式,不能是json字符串,如果是json字符串,写完之后就会多很多转义字符,如下图:

https://www.jb51.net/article/232125.htm