jQuery.parseJSON不适用于给定的字符串

Mat*_*att 0 javascript jquery parsing json

jQuery.parseJSON不适用于以下字符串:

({"stat":"OK","code":400,"data":[{"title":"Development Convention","event_type":false,"dates_and_times":[{"date":"28\/03\/2012","start_time":"10:00 AM","end_time":"10:00 AM"},{"date":"29\/03\/2012","start_time":"10:00 AM","end_time":"10:00 AM"},{"date":"30\/03\/2012","start_time":"12:00 PM","end_time":"12:00 PM"}],"description":"<p>This event will discuss different trends in development.<\/p>\n","featured_image":"<img src=\"http:\/\/mysite.com\/pesticide-free-organic-meal.jpg\" class=\"attachment-full wp-post-image\" alt=\"bavarian food plates with chicken and wine\" title=\"bavarian food plates with chicken and wine\" \/>","image_gallery":[{"url":"http:\/\/mysite.com","alt":false}]}]})
Run Code Online (Sandbox Code Playgroud)

这是我收到数据的地方:

$.get( 
    api_url, 
    { method: "list_events", venue_id: 73, event_date: 'null' }, 
    function( data ) {
        alert(data); // Shows the above string
        var response = jQuery.parseJSON( data );
        alert(1); // Doesn't appear
        alert(response.stat); // Doesn't appear             
    }
);
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供任何有关它可能无法正常工作的见解吗?我已经读过stackoverflow上的其他地方,反斜杠必须再次转义; 替换的所有实例\\\使用data = data.replace(/\\/g,"\\\\");并没有解决问题.

Fel*_*ing 5

你的字符串是无效的JSON,(并且)在那里无效.看起来该服务已设置为返回JSONP.

如果你包含?callback=?在URL中并使用$.getJSON [docs],那么jQuery将正确地进行所有解析.

例:

$.getJSON(
    api_url + '?callback=?', 
    { method: "list_events", venue_id: 73, event_date: 'null' }, 
    function( data ) {
        alert(data.stat);             
    }
);
Run Code Online (Sandbox Code Playgroud)

callback是标准参数名称,表示回调函数名称,但服务可能期望另一个.在这种情况下,请参阅其文档.

另请查看$.ajax [docs]以获取更多信息.


另一个但不太干净的解决方案是从括号中修剪开始和结束:

var response = $.parseJSON(data.replace(/^\(|\)$/g, ''));
Run Code Online (Sandbox Code Playgroud)

当然,如果服务位于同一个域上并且您可以控制它,则只需返回JSON即可.