我有以下JSON文件:
{"Mensaplan": [{
"Montag": [
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": false},
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": true, "bio": false},
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": false}
],
"Dienstag": [
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": false},
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": true},
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": false}
],
"Mittwoch": [
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": false},
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": true, "bio": false},
{"food": "Schnitzl", "price": "4.00 €", "vegetarian": false, "bio": true}
],
"Donnerstag": [
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": false},
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": false},
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": false}
],
"Freitag": [
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": false},
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": false},
{"food": "Schnitzl", "price": "5.00 €", "vegetarian": false, "bio": false}
]
}]
}
我想迭代“Mensaplan”并获得每一天(“Montag”,“Dienstag”,[...](它的德语))。我试图用jQuery Method $ .each来做这个,但我不知道如何制作一个通配符,因为每个人都有不同的名字。
任何人都可以帮我解决这个问题吗?
提前感谢!
答案 0 :(得分:6)
不需要jQuery,简单的for...in循环将起作用。
var obj = JSON.parse(yourJsonString);
//for each object in the "Mensaplan" array
for(var i = 0; i < obj.Mensaplan.length; ++i) {
//for each key in the object
for(var key in obj.Mensaplan[i]) {
var day = obj.Mensaplan[i][key];
//here key is the day's name, and day is the data...
}
}
希望这有帮助。
答案 1 :(得分:2)
首先使用JSON
var json = JSON.parse(jsonString)
然后只是一个javascript对象..你应该使用..
Object.keys(json).forEach(function (key) {
json[key];
});
如果您使用for in
,则需要检查该对象是否具有该属性且不是其父级之一(if (json.hasOwnProperty) { //code here }
)
使用Object.keys,您不需要这样做,因为只抓取对象拥有的键。
答案 2 :(得分:0)
var mensaplan = json['Mensaplan'];
for (key in mensaplan) {
values = mensaplan[key];
//do something with the values
}
答案 3 :(得分:0)
这里不需要jquery,一个简单的in就足够了,但是你必须检查hasOwnProperty函数,因为for in循环也可以检索对象的方法。
for (var key in Mensaplan) {
if (Mensaplan.hasOwnProperty(key) {
console.log(Mensaplan[key]);
}
}
UPDATE:在你的情况下,Mensaplan是一个包含在json中的数组...对于数组,最快的方法是循环的标准,而不是for for
for (var i = 0, length = Mensaplan.length; i < length; i++) {
console.log(Mensaplan[i]);
}