繁体   English   中英

将带有转义 unicode 的 json 文件转换为真正的 unicode,同时保留转义双引号

[英]Converting a json file with escaped unicode to real unicode while retaining escaped double quotes

我在 json 文件中有一个转义的 unicode 字符串,例如:

{"word": "\u043a\u043e\u0433\u0434\u0430 \u0440\u0430\u043a \u043d\u0430 \u0433\u043e\u0440\u0435 \u0441\u0432\u0438\u0441\u0442\u043d\u0435\u0442",
"glosses": ["when pigs fly, never (lit., \"when the crawfish whistles on the mountain\")"]}}

我想转换这个文件,以便显示正确的 unicode。 在 Python 中,我为此找到了几个建议,例如:

import codecs

# opens a file and converts input to true Unicode
with codecs.open("kaikki.org-dictionary-Russian.json", "rb", "unicode_escape") as my_input:
contents = my_input.read()
# type(contents) = unicode 

# opens a file with UTF-8 encoding
with codecs.open("utf8-dictionary.json", "wb", "utf8") as my_output:
my_output.write(contents)

我还编写了另一个类似的函数而不使用“编解码器”,但两者都得到了相同的结果。 执行命令后,我得到:

{"word": "когда рак на горе свистнет", 
"glosses": ["when pigs fly, never (lit., "when the crawfish whistles on the mountain")"]}

转义的双引号不再转义,这使得 JSON 无效。 我怎样才能防止这种情况?

编辑:我忘了提到我有一个 jsonlines 格式的文件,所以每一行都是一个以 { ... } 开头和结尾的 json 对象。

感谢所有的帮助! 我的最终解决方案:

import json

with open("kaikki.org-dictionary-Russian.json", "r", encoding="utf-8") as input, \
open("utf8-dictionary-4.json", "w", encoding="utf-8") as out:
for line in input:
    data = json.loads(line) 
    json.dump(data, out, ensure_ascii=False)
    out.write("\n")

使用json库处理 JSON 数据。 它将确保序列化数据是有效的 JSON,并且它有一些用于控制输出的选项,例如缩进的漂亮打印和不转义的非 ASCII 字符。

首先,使用json.load()解析数据:

>>> with open("kaikki.org-dictionary-Russian.json", encoding="utf8") as f:
...     data = json.load(f)

注意:在 Python 3 中,无需使用codecs库来读取/写入文件。 只需在内置的open函数中指定文件编码即可。

再次序列化数据,现在使用ensure_ascii选项,这导致转义序列的使用最少(只有双引号、换行符和制表符被转义 IIRC):

>>> with open("utf8-dictionary.json", "w", encoding="utf8") as f:
...     json.dump(data, f, ensure_ascii=False)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM