我有一个像这样的JSON字符串
var json = '{ "Comments":
[
{ "Id" : 1,"Comment" : "Test comment","Name" : "Yogesh","Child" : 0},
{ "Id" : 2,"Comment" : "Test comment II","Name" : "Yogesh","Child" : 0}
]
}';
我正试图迭代这些对象:
var parsedJSON = $.parseJSON(json);
var html = "";
for (comment in parsedJSON.Comments) {
html += "Id: " + comment.Id;
html += "Comment: " + comment.Comment;
html += "Name: " + comment.Name;
html += "Child: " + comment.Child;
html += "<br/>";
}
但for循环中的comment
只变为0
和1
,我的意思不是一个对象而只是一个字符串,我怎么能遍历这个数组呢?
答案 0 :(得分:4)
var json = '{ "Comments": [{ "Id" : 1,"Comment" : "Test comment","Name" : "Yogesh","Child" : 0},{ "Id" : 2,"Comment" : "Test comment II","Name" : "Yogesh","Child" : 0}] }';
var parsedJSON = $.parseJSON(json), // jsonData should json
html = "",
comments =parsedJSON.Comments; // keeping reference of parsedJSON and its an Array
// Here key will give 0, 1 etc ie. index of array
for (var key in comments) {
html += "Id: " + comments[key].Id;
html += "Comment: " + comments[key].Comment;
html += "Name: " + comments[key].Name;
html += "Child: " + comments[key].Child;
html += "<br/>";
}
<强> Demo 强>
答案 1 :(得分:2)
您似乎误解了for..in
循环的工作方式。 comment
将迭代地成为数组的键。在任何情况下,您都不应该在数组上使用for..in
,只能在对象上使用 - 甚至是谨慎使用。
var l = parsedJSON.Comments.length, i, comment;
for( i=0; i<l; i++) {
comment = parseJSON.Comments[i];
// do stuff with comment
}
答案 2 :(得分:0)
你可以试试这个:
var JsonData = { "Comments":
[
{ "Id" : 1,"Comment" : "Test comment","Name" : "Yogesh","Child" : 0},
{ "Id" : 2,"Comment" : "Test comment II","Name" : "Yogesh","Child" : 0}
]
};
var html = "";
for (var i = 0; i < JsonData.Comments.length; i++) {
comment = JsonData.Comments[i];
html += "Id: " + comment.Id;
html += " Comment: " + comment.Comment;
html += " Name: " + comment.Name;
html += " Child: " + comment.Child;
html += "<br/>";
}
alert(html);
答案 3 :(得分:0)
您可以使用$.each
:
var html = "";
$.each(parsedJSON.Comments, function(i, comment) {
html += "Id: " + comment.Id;
html += "Comment: " + comment.Comment;
html += "Name: " + comment.Name;
html += "Child: " + comment.Child;
html += "<br/>";
}
或者,您可以使用$.map
:
var html = $.map(parsedJSON.Comments, function(comment, i) {
return "Id: " + comment.Id +
"Comment: " + comment.Comment +
"Name: " + comment.Name +
"Child: " + comment.Child +
"<br/>";
}).join('');
答案 4 :(得分:0)
Comments包含一个包含两个元素的数组。
{ "Comments" : [ { 1 }, { 2 }] ...
所以你可以用
访问它for (var i = 0, len = parsedJSON.Comments.length; i < len; i++) {
html += "Id: " + parsedJSON.Comments[i].Id;
html += "Comment: " + parsedJSON.Comments[i].Comment;
html += "Name: " + parsedJSON.Comments[i].Name;
html += "Child: " + parsedJSON.Comments[i].Child;
html += "<br/>";
}