首页 > 解决方案 > 如何从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"
}

但我希望看到它像上面带有正确北欧字符的印刷品。我如何实现这一目标?

标签: jsonpython-2.7encoding

解决方案


你看到的是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.


推荐阅读