且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-09-05 12:05:10

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

第二个转义以JSON字符串文字形式转义。



Javascript表达式'{a:b:\\\c}'评估为字符串'{a:b:\c}'

此字符串包含单个未转义的 \ ,必须对JSON进行转义。为了获得一个包含 \\ 的字符串,每个 \ 必须在Javascript表达式中转义,结果在\\\\


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

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.

<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?

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

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 "\\\\".