简体   繁体   English

Unicode字符串转字节python 3

[英]Unicode string to bytes python 3

I have a Unicode string my_string = 'SGtjPQ\\\=\\\=' and a dictionary (2 backslashes) 我有一个Unicode字符串my_string ='SGtjPQ \\\\ u003d \\\\ u003d'和一个字典(2个反斜杠)

data = {'key': my_string}

I need to provide json-response in bytes, so I do the following 我需要提供以字节为单位的json-response,因此我需要执行以下操作

response = json.dumps(data)
return response.encode()

and eventually a have this result b'{"key": "SGtjPQ\\\\\\\=\\\\\\\="}' (4 backslashes). 最终a的结果为b'{“ key”:“ SGtjPQ \\\\\\\\ u003d \\\\\\\\ u003d”}' (4个反斜杠)。 But I want my_string in the response to be exactly as it was (with 2 backslashes). 但是我希望响应中的my_string完全一样(带有2个反斜杠)。 How to prevent this auto-escaping and get result b'{"key": "SGtjPQ\\\=\\\="}' 如何防止这种自动转义并获得结果b'{“ key”:“ SGtjPQ \\\\ u003d \\\\ u003d”}'

A backslash inside a JSON string is an escape character and itself needs to be escaped. JSON字符串中的反斜杠是转义字符,它本身需要转义。 "\\\\" inside JSON means a single backslash. JSON中的"\\\\" 表示单个反斜杠。 What you get, the four backslashes, is the correct JSON syntax for representing two backslashes. 您得到的四个反斜杠是代表两个反斜杠的正确JSON语法。

If you want it any differently, you should get your string in order before you JSON encode it. 如果您希望以其他方式进行更改,则在对JSON进行编码之前,应先按顺序获取字符串。 Don't write escaped JSON literal syntax, write the characters that you mean and let JSON encode it correctly for you. 不要编写转义的JSON文字语法,请写出您想要的字符,然后让JSON为您正确编码。

I'm not sure why you decided to put two backslashes in your python string in front of the code u003d. 我不确定为什么您决定在代码u003d前面的python字符串中添加两个反斜杠。 The syntax to specify unicode characters using their numeric code uses only one slash. 使用数字代码指定unicode字符的语法仅使用一个斜杠。 Like this: "SGtjPQ\=\=" 像这样: "SGtjPQ\=\="

Now, to answer your question about why you get the 4 slashes in the displayed string. 现在,回答关于为什么在显示的字符串中得到4个斜杠的问题。 This inflation of the number of backslashes is normal: 反斜杠数量的这种增加是正常的:

my_string in memory -> only one slash 内存中的my_string >仅一个斜杠

representation of my_string using Python syntax for strings -> two backslashes 使用Python语法为字符串表示my_string >两个反斜杠

representation of my_string in json -> two backslashes json中my_string表示形式->两个反斜杠

representation (using Python syntax for strings) of the json representation of my_string -> 4 backslashes my_string > 4个反斜杠的json表示形式(使用Python语法表示字符串)

So you have 4 backslashes in the end result because the slash is first escaped by the JSON encoding, and then, the two resulting slashes are escaped by the display of the python interpreter, which displays strings using the Python syntax for strings. 因此,最终结果中有4个反斜杠,因为该斜杠首先被JSON编码转义,然后,两个生成的斜杠被python解释器的显示转义,该解释器使用Python语法对字符串进行显示。

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

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