由于JSON中的单引号转义,jQuery.parseJSON抛出“无效的JSON”错误 [英] jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

查看:1027
本文介绍了由于JSON中的单引号转义,jQuery.parseJSON抛出“无效的JSON”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery.post()向我的服务器发出请求,而我的服务器正在返回JSON对象(例如 {var: value,...} )。但是,如果任何值包含单引号(正确转义,如 \'),则jQuery无法解析其他有效的JSON字符串。这是我的意思的一个例子( JSON for Java的实现更加允许, 允许单引号字符:


toString方法生成的文本严格符合JSON语法规则。构造函数在他们接受的文本中更宽容:



...




  • 字符串可以用'(单引号)引用。


这是由< a href =https://github.com/douglascrockford/JSON-java/blob/master/JSONTokener.java =noreferrer> JSONTokener 源代码。 nextString 方法接受转义的单引号字符,并将它们视为双引号字符:

  public String nextString(char quote)抛出JSONException {
char c;
StringBuffer sb = new StringBuffer();
for(;;){
c = next();
开关(c){

...

case'\\':
c = this.next();
开关(c){

...

case'':
case'\'':
case' \\':
case'/':
sb.append(c);
break;
...

该方法的顶部是一条内容丰富的评论:


正式的JSON格式不允许单引号中的字符串,但允许实现接受它们。


因此一些实现将接受单引号 - 但你不应该依赖于此。许多流行的实现在这方面是相当严格的,并将拒绝包含单引号字符串和/或转义单引号的JSON。






最后要将其与原始问题联系起来, jQuery.parseJSON 首次尝试使用浏览器的本机JSON解析器或加载的库,如 json2.js 在适用的情况下(如果没有定义 JSON ,那么jQuery逻辑所依据的是库)。因此jQuery只能像底层实现一样宽松:

  parseJSON:function(data){
...

//首先尝试使用本机JSON解析器进行解析
if(window.JSON&& window.JSON.parse){
return window.JSON.parse(数据);
}

...

jQuery.error(无效的JSON:+数据);
},

据我所知,这些实现仅遵循官方JSON规范和不接受单引号,因此jQuery也不接受。


I’m making requests to my server using jQuery.post() and my server is returning JSON objects (like { "var": "value", ... }). However, if any of the values contains a single quote (properly escaped like \'), jQuery fails to parse an otherwise valid JSON string. Here’s an example of what I mean (done in Chrome’s console):

data = "{ \"status\": \"success\", \"newHtml\": \"Hello \\\'x\" }";
eval("x = " + data); // { newHtml: "Hello 'x", status: "success" }

$.parseJSON(data); // Invalid JSON: { "status": "success", "newHtml": "Hello \'x" }

Is this normal? Is there no way to properly pass a single quote via JSON?

解决方案

According to the state machine diagram on the JSON website, only escaped double-quote characters are allowed, not single-quotes. Single quote characters do not need to be escaped:


Update - More information for those that are interested:


Douglas Crockford does not specifically say why the JSON specification does not allow escaped single quotes within strings. However, during his discussion of JSON in Appendix E of JavaScript: The Good Parts, he writes:

JSON's design goals were to be minimal, portable, textual, and a subset of JavaScript. The less we need to agree on in order to interoperate, the more easily we can interoperate.

So perhaps he decided to only allow strings to be defined using double-quotes since this is one less rule that all JSON implementations must agree on. As a result, it is impossible for a single quote character within a string to accidentally terminate the string, because by definition a string can only be terminated by a double-quote character. Hence there is no need to allow escaping of a single quote character in the formal specification.


Digging a little bit deeper, Crockford's org.json implementation of JSON for Java is more permissible and does allow single quote characters:

The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more forgiving in the texts they will accept:

...

  • Strings may be quoted with ' (single quote).

This is confirmed by the JSONTokener source code. The nextString method accepts escaped single quote characters and treats them just like double-quote characters:

public String nextString(char quote) throws JSONException {
    char c;
    StringBuffer sb = new StringBuffer();
    for (;;) {
        c = next();
        switch (c) {

        ...

        case '\\':
            c = this.next();
            switch (c) {

            ...

            case '"':
            case '\'':
            case '\\':
            case '/':
                sb.append(c);
                break;
        ...

At the top of the method is an informative comment:

The formal JSON format does not allow strings in single quotes, but an implementation is allowed to accept them.

So some implementations will accept single quotes - but you should not rely on this. Many popular implementations are quite restrictive in this regard and will reject JSON that contains single quoted strings and/or escaped single quotes.


Finally to tie this back to the original question, jQuery.parseJSON first attempts to use the browser's native JSON parser or a loaded library such as json2.js where applicable (which on a side note is the library the jQuery logic is based on if JSON is not defined). Thus jQuery can only be as permissive as that underlying implementation:

parseJSON: function( data ) {
    ...

    // Attempt to parse using the native JSON parser first
    if ( window.JSON && window.JSON.parse ) {
        return window.JSON.parse( data );
    }

    ...

    jQuery.error( "Invalid JSON: " + data );
},

As far as I know these implementations only adhere to the official JSON specification and do not accept single quotes, hence neither does jQuery.

这篇关于由于JSON中的单引号转义,jQuery.parseJSON抛出“无效的JSON”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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