【发布时间】:2021-09-24 16:50:51
【问题描述】:
我在 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")
【问题讨论】:
标签: python json unicode encoding