为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

ITMISS 2023-10-26 17:03:39
您好,我在 Python 中将 utf-8 json 转换为 unicode escape json 时遇到一些麻烦我知道如何将 utf-8.txt 转换为 unicode escape.txtwith 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”格式编写文件时才会发生这种情况。 并用奇数个反斜杠替换原始字符串将不起作用。任何建议或想法将不胜感激!
查看完整描述

1 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

看起来你只是想要ensure_ascii=True(默认):


C:\>type input.json

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


C:\>py

Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32

Type "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)

...

>>> ^Z


C:\>type output.json

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


查看完整回答
反对 回复 2023-10-26
  • 1 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信