【问题标题】:Converting a json file with escaped unicode to real unicode while retaining escaped double quotes将带有转义 unicode 的 json 文件转换为真正的 unicode,同时保留转义的双引号
【发布时间】: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


    【解决方案1】:

    使用 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)
    

    【讨论】:

    • 感谢您的帮助!我忘了提到我有一个 jsonlines 格式的文件,所以每一行都是一个以 { ... } 开头和结尾的 json 对象。这意味着我很遗憾无法将其直接加载到 json.load 函数中。
    • @Pux 好的,然后逐行遍历文件并使用json.loads
    • @juanpa.arrivillaga 哦,谢谢,我忘了有这个功能。
    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多