javascript 为什么 jQuery JSON 解析器需要对反斜杠进行双重转义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3807537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:18:59  来源:igfitidea点击:

Why does the jQuery JSON parser need double escaping for backslashes?

javascriptjqueryjsondata-structures

提问by Saul

I have trouble wrapping my head around a peculiar feature of the JSON data format.

我无法理解 JSON 数据格式的一个特殊功能。

The situation is as follows: I have a string containing a Windows (sigh) directory path, backslashes escaped. For some reason, the jQuery JSON parser thinks that a single escape is not enough.

情况如下:我有一个包含 Windows ( sigh) 目录路径的字符串,转义了反斜杠。出于某种原因,jQuery JSON 解析器认为单个转义是不够的。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">

var success = jQuery.parseJSON('{"a":"b:\\c"}');
var failure = jQuery.parseJSON('{"a":"b:\c"}');

</script>

Can anyone explain what makes such double escaping necessary?

谁能解释一下是什么让这种双重转义变得必要?

回答by SLaks

The first escape escapes it in the Javascript string literal.
The second escape escapes it in the JSON string literal.

第一个转义在 Javascript 字符串文字中转义它。
第二个转义在 JSON 字符串文字中转义它。

The Javascript expression '{"a":"b:\\c"}'evaluates to the string '{"a":"b:\c"}'.
This string contains a single unescaped \, which must be escaped for JSON. In order to get a string containing \\, each \must be escaped in the Javascript expression, resulting in "\\\\".

Javascript 表达式的'{"a":"b:\\c"}'计算结果为 string '{"a":"b:\c"}'
此字符串包含单个未转义的\,必须为 JSON 转义。为了获得包含 的字符串\\,每个字符串都\必须在 Javascript 表达式中进行转义,从而生成"\\\\".