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

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

问题描述

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

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

情况如下:我有一个包含 Windows (sigh) 目录路径的字符串,反斜杠被转义.出于某种原因,jQuery 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.

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

推荐答案

第一个转义在 Javascript 字符串文字中对其进行转义.
第二个转义在 JSON 字符串文字中转义它.

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

Javascript 表达式 '{"a":"b:\c"}' 计算结果为字符串 '{"a":"b:c"}'.
此字符串包含单个未转义的 ,对于 JSON,必须对其进行转义.为了得到一个包含 \ 的字符串,每个 都必须在 Javascript 表达式中转义,结果是 "\\".

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天全站免登陆