Single vs. Double Quotes in jQuery.parseJSON
In JavaScript, the jQuery.parseJSON method converts a JSON string into a JavaScript object. When working with JSON strings, it's crucial to understand the difference between using single and double quotes.
The Issue
The code snippet below works successfully:
var obj1 = jQuery.parseJSON('{"orderedList": "true"}');
However, the following code fails to parse the JSON string:
var obj2 = jQuery.parseJSON("{'orderedList': 'true'}");
The Reason
The discrepancy arises from the different handling of single and double quotes in JSON syntax. According to the JSON standard, double quotes are considered the standard for string delimiters, while single quotes are not.
JSON Syntax
The JSON syntax specifies that:
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
因此,在 JSON 字符串中使用双引号时,JavaScript 才能正确解析它。单引号不被视为有效的字符串定界符,导致 jQuery.parseJSON 无法正确转换 JSON 字符串。
更新
值得注意的是,类似的问题曾在 jQuery 社区的讨论中出现过,即在 JSON 响应中使用单引号。解决这个问题的一种方法是確保在 JSON 字符串中始终使用双引号。
以上是为什么双引号和单引号在 jQuery.parseJSON 中的行为不同?的详细内容。更多信息请关注PHP中文网其他相关文章!