为什么jQuery JSON解析器需要双重转义为反斜杠? [英] Why does the jQuery JSON parser need double escaping for backslashes?

查看:722
本文介绍了为什么jQuery JSON解析器需要双重转义为反斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



情况如下:我有一个包含Windows(叹息)目录路径,反斜杠转义。由于某种原因,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>

任何人都可以解释什么使得这种双重转义是必要的?

解决方案

第一个转义在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 "\\\\".

这篇关于为什么jQuery JSON解析器需要双重转义为反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆