json - 如何从python将北欧字符写入json文件?
问题描述
假设我在 python 中有以下示例
import json
In [46]: d = {'test': u'Fors\xf8g'}
In [47]: print(d['test'])
Forsøg
In [48]: with open('da.json', 'w') as f:
...: json.dump(d, f, sort_keys=True, indent=4)
...:
打开该 json 文件,我看到以下内容。
{
"test": "Fors\u00f8g"
}
但我希望看到它像上面带有正确北欧字符的印刷品。我如何实现这一目标?
解决方案
你看到的是100%正确的。JSON 允许仅包含 ASCII 字符的字符串并将所有“扩展”字符转义为\u
+ Unicode 字符代码。
当您或其他任何人再次解析文件时,将出现正确的字母。你不需要做任何事情,真的。
如果您绝对不喜欢它的外观,则需要将 JSON 文件编写为 UTF-8。这也有效,但 Python 2.7open()
没有给你文件编码选择(Python 3+ 有)。
您可以使用codecs.open()
,它可以轻松处理 UTF-8 文件:
import codecs
import json
d = {'test': u'Fors\xf8g'}
with codecs.open('da.json', 'w', encoding='utf8') as f:
json.dump(d, f, sort_keys=True, indent=4, ensure_ascii=False)
Since json.dump()
is responsible for the escaped characters, we need to tell it to not do that with ensure_ascii=False
.
推荐阅读
- openlayers - 是否可以只渲染视口内的那些图层?
- android - 使用 Android Q 拒绝 AndroidAudioConverter 权限
- python - 用系列更新 pandas DataFrame 多级索引?
- visual-studio-code - VSCode:/usr/bin/node:错误选项:--inspect 自上次升级以来?
- scala - Kafka Streams DSL:如何关闭由流分支/分组创建的子流?
- javascript - 从复杂字符串中提取文本
- javascript - 协助存根类内的函数
- c# - 尝试激活 SecurityStampValidator 时无法解析 ISystemClock 的服务
- pg-promise - 跳过未在源中传递的更新列
- c++ - 为什么在我的值迭代算法中变量赋值要花费这么多时间?