问题与背景

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

  • dict 转 json字符串
  • json字符串 转 dict
  • dict类型写入json文件
  • json文件读取为dict类型

解决方案与总结

变量类型的映射

python中json的使用_开发语言

dict与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))

输出为:

<class 'dict'>
{"name": "Tom", "age": 18, "score": {"math": 98, "chinese": 99}}
<class 'str'>
{'name': 'Tom', 'age': 18, 'score': {'math': 98, 'chinese': 99}}
<class 'dict'>

dict与json文件读写

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字符串,写完之后就会多很多转义字符,如下图:

python中json的使用_json_02

参考资料

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