简体   繁体   English

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

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

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. 情况如下:我有一个包含Windows( 叹息 )目录路径的字符串,反斜杠转义。 For some reason, the jQuery JSON parser thinks that a single escape is not enough. 出于某种原因,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? 任何人都可以解释是什么让这种双重逃避变得必要吗?

The first escape escapes it in the Javascript string literal. 第一个转义符在Javascript字符串文字中转义它。
The second escape escapes it in the JSON string literal. 第二个转义符在JSON字符串文字中转义它。

The Javascript expression '{"a":"b:\\\\c"}' evaluates to the string '{"a":"b:\\c"}' . Javascript表达式'{"a":"b:\\\\c"}'计算为字符串'{"a":"b:\\c"}'
This string contains a single unescaped \\ , which must be escaped for JSON. 此字符串包含单个未转义的\\ ,必须为JSON转义。 In order to get a string containing \\\\ , each \\ must be escaped in the Javascript expression, resulting in "\\\\\\\\" . 为了获得包含\\\\的字符串,每个\\必须在Javascript表达式中进行转义,从而产生"\\\\\\\\"

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

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