JSON中的引号抛出jQuery错误,即使它们被转义

时间:2016-12-09 14:43:30

标签: php jquery json

我正在使用PHP获取存储在MySQL数据库中的JSON,将其放入PHP变量中,并将其传递给JQuery,后者将内容写入页面:

data = $.parseJSON('<?=$my_json;?>'); 
$.each(data.links, function(entryIndex, entry) {
    //do some stuff here
        });

当JSON看起来像这样时,一切正常:

{
    "links": [{
        "url": "http://domain1.com",
        "title": "Title 1",
        "description": "This is an example for my question on Stack Overflow"
    }, {
        "url": "http://domain2.com",
        "title": "Title 2",
        "description": "This is another example for my question on Stack Overflow"
    }, {
        "url": "http://domain3.com",
        "title": "Title 3",
        "description": "This is a third example for my question on Stack Overflow"
    }]
}

但是当JSON内容包含引号时,我得到一个错误,读取“Uncaught SyntaxError:JSON输入的意外结束”,即使引号被转义,如下所示:

{
    "links": [{
        "url": "http://domain1.com",
        "title": "Title 1",
        "description": "This is an \"example\" for my question on Stack Overflow"
    }, {
        "url": "http://domain2.com",
        "title": "Title 2",
        "description": "This is another \"example\" for my question on Stack Overflow"
    }, {
        "url": "http://domain3.com",
        "title": "Title 3",
        "description": "This is a third \"example\" for my question on Stack Overflow"
    }]
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

data = $.parseJSON('<?=$my_json;?>');

你在这里做的事情是你试图围绕引号包装JavaScript对象并将其作为字符串传递给$.parseJSON函数。

此函数仅解析JSON字符串,该字符串应使用JSON结构形成,然后由函数转换为JavaScript对象。

虽然$my_json变量已有JavaScript对象,但您不需要使用$.parseJSON函数。您可以将它分配给JavaScript变量,如下所示:

data = <?= $my_json ?>; 
$.each(data.links, function(entryIndex, entry) {
    //do some stuff here
});