写入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'>
天气好
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐