Python-Json模块用法详解

Yishto 2021-08-20 21:46:30
Categories: Tags:

import json

1
2
3
4
5
6
7
8
9
dic = {'a':1, 'b':2, 'c':3}
# 把dic转换成json字符串
# ensure_ascii=False 是关闭把中文转换成ASCII
# indent=4 写入到文件中自动格式化
json_str = json.dumps(ret1, ensure_ascii=False, indent=4)
with open('xxx.json', 'w', encoding='utf-8') as f:
# 把json字符串写入文件,或者返回给前端等等
f.write(json_str)

1
2
3
4
with open('xxx.json', 'r', encoding='utf-8') as f:
json_str = f.read()
dic = json.loads(json_str) # 转换为python类型

1
2
3
with open('xxx.json', 'r', encoding='utf-8') as f:
dic = json.load(f) # 从json文件反序列化到python类型

1
2
3
4
dic = {'a':1, 'b':2, 'c':3}
with open('xxx.json', 'w', encoding='utf-8') as f:
json.dump(dic, f) # 把python类型序列化到文件对象中

其他知识点: