我有一个像这样的对象
var JSON_Object = {
"Diabites": [
{
"Day1": [
{
"Breakfast": [
{
"food1": "Bread",
"food2": "Tea",
"food3": "Edd"
}
]
},
{
"Lunch": [
{
"food1": "Bread",
"food2": "Tea",
"food3": "Edd"
}
]
},
{
"Dinner": [
{
"food1": "Bread",
"food2": "Tea",
"food3": "Edd"
}
]
}
]
},
{
"Day2": [
{
"Breakfast": [
{
"food1": "Bread",
"food2": "Tea",
"food3": "Edd"
}
]
},
{
"Lunch": [
{
"food1": "Bread",
"food2": "Tea",
"food3": "Edd"
}
]
},
{
"Dinner": [
{
"food1": "Bread",
"food2": "Tea",
"food3": "Edd"
}
]
}
]
}
]
}
现在我如何使用一些循环打印出来读取此文件。我尝试了以下
alert(JSON_Object.Diabites.length); // Return 1
alert(JSON_Object.Diabites[0].Day1.length); // Return 3
但是有Day1, Day2, Day3 ....
等不同的名称,所以如何在循环中更改该部分,如
for(var i=0; i<JSON_Object.Diabites.length;i++)
{
alert(JSON_Object.Diabites[i].Day1.length);
}
更新JSON对象
var JSON_Object = {
"Diabites": [
{
"Day1": [
{
"Breakfast": [
{
"food1": "Bread"
},
{
"food2": "Tea"
},
{
"food3": "Edd"
}
]
},
{
"Lunch": [
{
"food1": "Bread"
},
{
"food2": "Tea"
},
{
"food3": "Edd"
}
]
},
{
"Dinner": [
{
"food1": "Bread"
},
{
"food2": "Tea"
},
{
"food3": "Edd"
}
]
}
]
},
{
"Day2": [
{
"Breakfast": [
{
"food1": "Bread"
},
{
"food2": "Tea"
},
{
"food3": "Edd"
}
]
},
{
"Lunch": [
{
"food1": "Bread"
},
{
"food2": "Tea"
},
{
"food3": "Edd"
}
]
},
{
"Dinner": [
{
"food1": "Bread"
},
{
"food2": "Tea"
},
{
"food3": "Edd"
}
]
}
]
}
]
};
答案 0 :(得分:1)
如果你想循环json的键,你可以这样做
for(var key in JSON_Object.Diabites[0]){
//key will be Day1,Day2 etc.
alert(JSON_Object.Diabites[0][key].length);
}
但是在你的json结构中,你必须使用
for(var i=0;i<JSON_Object.Diabites.length;i++) {
for(var key in JSON_Object.Diabites[i]) {
//key will be Day1,Day2 etc.
alert(key);
alert(JSON_Object.Diabites[i][key].length);
}
}
here is a working fiddle如果您有兴趣。