读取一个含中文的文件,再写到另一个文件(用的json.dump()),出现了中文被转成Unicode的问题,要注意设置参数:ensure_ascii=False
with open("../module.json", "r", encoding= "utf-8") as f:
moduleconf_content = f.read()
moduleconf_json = json.loads(moduleconf_content)
moduleconf_json["a"] = "aa"
with open(package_config_filepath, "r", encoding= "utf-8") as f:
package_config_content = f.read()
content_json = json.loads(package_config_content)
content_str = json.dumps(moduleconf_json, ensure_ascii=False)
content_json["b"] = content_str
with open(package_config_filepath, "w", encoding="utf-8") as f:
json.dump(content_json, f, ensure_ascii=False, indent=4)
如果无任何配置,或者说使用默认配置,输出的会是ASCII字符,而不是真正的中文,这是因为json.dumps 序列化时对中文默认使用的ASCII编码
>>> print(json.dumps("中国"))
"中国"
>>> print(json.dumps("中国", ensure_ascii=False))
"中国"