将 json -(utf-8) 转换为 json(unicode escape) 和原始字符串

您好,我在 Python 中将 utf-8 json 转换为 unicode escape json 时遇到一些麻烦


我知道如何将 utf-8.txt 转换为 unicode escape.txt


with open("input.txt", "r", encoding='utf8') as f:

    text = f.read()


with open('output.txt', 'w', encoding='unicode-escape') as f:

    f.write(text)

但是,我面临着上面使用 python 中的 json 模块应用的问题,如下所示


with codecs.open(self.input,'r', encoding='utf-8') as json_file:

    json_data = json.load(json_file)


with codecs.open(self.output,'w', encoding='unicode-escape') as json_file:

    prepare_json = json.dumps(json_data, ensure_ascii=False)

    json_file.write(prepare_json)

它保存得很好,但是当涉及到 json 中的双引号 (") 时,它会自动添加双反斜杠 (\\),因此在 python 脚本中调用时 unicode-escape.json 文件无法正常工作。


认为


1. Input file (UTF-8): {"context" : "-\" 너"} 

我通过上面的第二个代码块转换它


2. Output file (UNICODE-ESCAPED) : {"context" : "-\\" \ub108"}

3. What I want (UNICODE-ESCAPED) : {"context" : "-\" \ub108"}

由于双引号前面有双反斜杠,Python 在加载 unicode 转义的 json 文件时会显示错误。


更多细节


输入文件:./simple_test.json


{"context" : "-\" 너"}

with codecs.open('./simple_test.json', 'r', encoding='utf-8') as json_file:

    json_data = json.load(json_file)


prepare_json = json.dumps(json_data, ensure_ascii=False)

prepare_json

>>> '{"context": "-\\" 너"}'

repr(prepare_json)

>>> '\'{"context": "-\\\\" 너"}\''

print(prepare_json)

>>> {"context": "-\" 너"} 

所以它应该打印出 {"context": "-" \ub108"} ,这只是 {"context": "-" 너"} 。


Output.json(I excpected}

{"context": "-\" \ub108"}

但是,使用下面的代码我得到了


with codecs.open('./simple_test_out.json','w', encoding='unicode-escape') as json_file:

    json_file.write(prepare_json)

Output.json

{"context": "-\\" \ub108"}

经过几次尝试,我发现只有在使用encoding =“unicode-escape”格式编写文件时才会发生这种情况。 并用奇数个反斜杠替换原始字符串将不起作用。


任何建议或想法将不胜感激!


ITMISS
浏览 93回答 1
1回答

撒科打诨

看起来你只是想要ensure_ascii=True(默认):C:\>type input.json{"context" : "-\" 너"}C:\>pyPython 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import json>>> with open('input.json',encoding='utf8') as f:...    data = json.load(f)...>>> data{'context': '-" 너'}>>> with open('output.json','w',encoding='utf8') as f:...    json.dump(data,f)...>>> ^ZC:\>type output.json{"context": "-\" \ub108"}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python