jQuery解析JSON出现SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

时间:2023-03-09 13:23:18
jQuery解析JSON出现SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

我在使用$.parseJSON解析后台返回的JSON的数据时,出现了这样的错误,我还以为返回的JSON格式出现了错误,因为JSON要求格式非常严格。最后发现JSON格式没有太明显的格式错误,我使用fastJSON来生成的JSON格式数据,原来是因为数据已经是一个JavaScript对象了,所以在进行解析就会出错了

我直接将这段数据alert出来,并使用typeof检验其类型,发现是一个Object,这就证明了数据已成为了JavaScript对象了。所以,我直接使用(不用什么parseJSON解析了)这段数据进行相应的处理就不会出错

   $.ajax({
url : 'commentAction_showComment',
type : 'POST',
data:{
titleid: $(comment_this).attr('data-id'),
currPage : currPage,
},
beforeSend : function (jqXHR, settings) {
$('.comment_list').eq(index).append('<dl class="comment_load"><dd>正在加载评论</dd></dl>');
},
success : function (response, status) {
var json_comment = response;
},
});

也许是我对jQuery的parseJSON方法理解错误使用不当,或者是该用其他的方法处理?

后台响应的是JSON格式的字符串而不是JSON对象

如果后台发送的是一个JSON格式的字符串(注意:是字符串,只是采用JSON的语法格式,不是JSON数据),我们在前台应该怎样解析成一个JSON对象呢?

后台代码:

        PrintWriter out = response.getWriter();
String username = request.getParameter("user");
String password = request.getParameter("pwd");
String data = "{'username':'"+username+"','password':'"+password+"'}";
System.out.println(data);
out.write(data);

这个data就是一个JSON格式的字符串

我们需要将eval()方法将这个字符串包一下,就可以转成JSON对象了,eval应该是一个JavaScript中的方法:

$.ajax({ //一个Ajax过程
type : "post", //以post方式与后台沟通
url : "Ajax_jQueryServlet", //与此php页面沟通
data : 'username=' + username + '&password=' + password,
success : function(data) {
var json = eval('(' + data + ')');
$('#result').html(
"姓名:" + json.username + "<br/>密码:" + json.password);
}
});

注:eval('('+text+')')将JSON格式的字符串text解析为成具体的类型,如boolean什么的,有时可能需要使用eval('['+text+']')  方括号来包裹JSON字符串,可以解析为数组,也就是Object类型。具体使用看情况吧