在读取包含中文的 JSON 文件时,需要指定文件的编码格式,否则可能会导致乱码。可以使用 json 库来读取文件,代码如下:
方法一
在读取json文件时,使用ensure_ascii=False参数,即
import json
# 指定文件编码格式为 UTF-8
with open("file.json", "r", encoding="UTF-8") as f:
data = json.load(f)
# 可以使用读取到的数据进行处理
print(data)
方法二
用codecs模块,即
import codecs
import json
file=codecs.open(filename,encoding='utf-8')
data = json.load(file)
如果想写入包含中文的 JSON 文件,也需要指定编码格式:
import json
data = {"key": "值"}
# 指定文件编码格式为 UTF-8
with open("file.json", "w", encoding="UTF-8") as f:
json.dump(data, f, ensure_ascii=False)