简体   繁体   English

在JavaScript和Python 2.7中的JSON字符串中转义反斜杠

[英]Escape backslash in JSON String in JavaScript and Python 2.7

Here is my JSON string to loads or Parse: 这是我要加载或解析的JSON字符串:

json_str = '[{"executable_path": "C:\\GCafeClient\\CafeClient.exe", "arguments": "-package 100003"}]'

This was valid if I test it in json formatter or here (Also it makes sense right--I have escaped backslash. 如果我在json格式化程序中此处进行测试,则这是有效的(而且这很合理-我已经转义了反斜杠。

But when I do json.loads(json_str) in Python 2.7 or JSON.parse(json_str) in JavaScript in Chrome. 但是当我在Python 2.7中执行json.loads(json_str)或在Chrome中的JavaScript中执行JSON.parse(json_str)时。 I got errors: 我有错误:

ValueError: Invalid \escape: line 1 column 25 (char 24)

and

Uncaught SyntaxError: Unexpected token G

If I put it this way, then it will work for both: 如果我这样说的话,它将对两个都起作用:

json_str = '[{"executable_path": "C:\\\\GCafeClient\\\\CafeClient.exe", "arguments": "-package 100003"}]'

Why is this so? 为什么会这样呢?

I will just post my own understanding here for this question: 对于这个问题,我将在这里发表自己的理解:

# python
json_str = '[{"executable_path": "C:\\\\GCafeClient\\\\CafeClient.exe", "arguments": "-package 100003"}]'
# which is equivalent to
json_str = r'[{"executable_path": "C:\\GCafeClient\\CafeClient.exe", "arguments": "-package 100003"}]'
# and JSON format requires backslash to be escaped

You need to escape the '\\' twice, the first time for the Python/JavaScript literal and the second time for JSON. 您需要两次对“ \\”进行转义,第一次是使用Python / JavaScript文字,第二次是JSON。

So "C:\\\\GCafeClient" will evaluate to "C:\\GCafeClient" , which is not accepted JSON as it contains an unescaped '\\' and will throw an error. 因此, "C:\\\\GCafeClient"计算结果为"C:\\GCafeClient" ,因为它包含未转义的'\\',所以不接受JSON,并会引发错误。

On the other hand "C:\\\\\\\\GCafeClient" will evaluate to the JSON being "C:\\\\GCafeClient" , therefore the '\\' is escaped and accepted. 另一方面, "C:\\\\\\\\GCafeClient"将评估为JSON,即"C:\\\\GCafeClient" ,因此'\\'被转义并被接受。

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

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