python json的中文读取与中文写入
·
写入json
import json
# 写入json
all_res = {}
write_path = "E:/test_feature.json"
all_res["明天"] = "天气好"
with open(write_path, "w", encoding='utf-8') as f:
json.dump(all_res, f, ensure_ascii=False)
文件test_feature.json
内容:
{"明天": "天气好"}
中文的写入 json.dump
需要加上ensure_ascii=False
参数。否则默认写入unicode
{"\u660e\u5929": "\u5929\u6c14\u597d"}
这里 查询不同编码之间的转换:
读取json
write_path = "E:/test_feature.json"
with open(write_path, encoding="utf-8") as f:
res = json.load(f)
print(type(res))
print(res['明天'])
读取文件时,需要加上encoding="utf-8"
,否则会出现错误UnicodeDecodeError: 'gbk' codec can't decode byte 0xbd in position 20: illegal multibyte sequence
<class 'dict'>
天气好
更多推荐
已为社区贡献9条内容
所有评论(0)