我已经想过如何遍历以下here的JSON:
{"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150"},{"entryID":"4","distance":"400","calories":"200"},{"entryID":"5","distance":"500","calories":"250"},{"entryID":"6","distance":"600","calories":"300"}],"success":1}
这是我如何做到的:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
myLogger(jsonarray[key].entryID + " - " + jsonarray[key].distance + " - " + jsonarray[key].calories);
}
}
但是JSON在for循环中检查失败了。
我的JSON数据有什么问题?
我的目标是使用上面的for循环将数据添加到google.visualization.DataTable(),如下所示:
data = new google.visualization.DataTable();
data.addColumn('number', 'distance');
data.addColumn('number', 'calories');
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
//data.addRow(jsonarray[key].distance);
//data.addRow(jsonarray[key].calories);
}
}
答案 0 :(得分:1)
如果您知道哪个属性包含您需要的集合(working example - jsbin):
var obj = {"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150"},{"entryID":"4","distance":"400","calories":"200"},{"entryID":"5","distance":"500","calories":"250"},{"entryID":"6","distance":"600","calories":"300"}],"success":1};
for (var key in obj.dummmysetsJSONArr) {
if (obj.dummmysetsJSONArr.hasOwnProperty(key)) {
document.write(obj.dummmysetsJSONArr[key].distance + " " + obj.dummmysetsJSONArr[key].calories);
document.write("<br/>");
}
}
在其他情况下,最好的方法是找到所有具有entryId,distance和caloreis属性的对象,因为你的json可能有更多数组(我不知道这是动态json还是什么)
答案 1 :(得分:0)
看起来您需要对键/值进行多次迭代。 第一次迭代将为您提供键'dummmysetsJSONArr'和数组作为值。
然后你想迭代数组,每个键都是索引,值就是对象。
对值的下一次迭代将为您提供对象的属性名称和值。
答案 2 :(得分:0)
该物业&#34; dummmysetsJSONArr&#34;不是一个对象而是一个数组,所以你可以这样做:
var myObj = {"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150"},{"entryID":"4","distance":"400","calories":"200"},{"entryID":"5","distance":"500","calories":"250"},{"entryID":"6","distance":"600","calories":"300"}],"success":1}
var obj = myObj.dummmysetsJSONArr; //this is an array not an object
var str = "";
for (var i=0;i< obj.length;i++) {
str += obj[i].entryID + " - " + obj[i].distance + " - " + obj[i].calories+"<br>";
}
但是,JavaScript中的数组只是具有数字键的对象,因此您可以这样做:
var obj = myObj.dummmysetsJSONArr; //this is an array not an object
var str = "";
for (key in obj) {
str += obj[key].entryID + " - " + obj[key].distance + " - " + obj[key].calories+"<br>";
}
检查hasOwnProperty没有多大意义,因为你的JSON对象只是一个普通的对象而且每个属性都是它自己的属性