我遇到了从 Web 服务返回的 JSON 的问题。看起来 JSON 缺少引号,但是当我向 JSON 添加引号时,出现错误。这是错误消息:'Uncaught SyntaxError: Unexpected token o。当我将字符串记录到控制台时:[object Object],[object Object]
这是一些模拟错误的示例代码:
//Error I am trying to solve
var jsonString = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
var myData = JSON.parse(jsonString);
$(document).ready(function() {
var $grouplist = $('#groups');
$.each(myData, function() {
$('<li>' + this.Name + '</li>').appendTo($grouplist);
});
});
这是与字符串周围的单引号相同的代码。有用
//Successful Javascript
var jsonString = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
var myData = JSON.parse(jsonString);
$(document).ready(function() {
var $grouplist = $('#groups');
$.each(myData, function() {
$('<li>' + this.Name + '</li>').appendTo($grouplist);
});
});
//Successful HTML
<ul id="groups"></ul>
但是当我尝试在字符串中添加引号时,就像我在真实代码中似乎需要的那样,它失败了:
//Does not work when I need to append quotes to the string:
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
jsonStringQuotes = "'" + jsonStringNoQuotes + "'";
var myData = JSON.parse(jsonStringQuotes);
$(document).ready(function() {
var $grouplist = $('#groups');
$.each(myData, function() {
$('<li>' + this.Name + ',' + this.Id + '</li>').appendTo($grouplist);
});
});
这是错误:将字符串记录到控制台:[object Object],[object Object] data.js:809 Uncaught SyntaxError: Unexpected token '
我难住了。任何帮助表示赞赏!谢谢!