6

我有以下 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 方法 $.each 来做到这一点,但我不知道如何为这些日子制定通配符,因为每个通配符都有不同的名称。

谁能帮我解决这个问题?

预先感谢!

4

4 回答 4

7

不需要 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...

    }

}

希望这可以帮助。

于 2013-08-22T15:56:33.107 回答
3

首先使用解析它JSON

var json = JSON.parse(jsonString)

然后只是一个javascript对象..你应该使用..

Object.keys(json).forEach(function (key) {
    json[key];  
});

如果您使用for in,您需要检查该对象是否具有该属性并且不是其父对象之一(if (json.hasOwnProperty) { //code here }

使用 Object.keys 你不需要这样做,因为只获取对象拥有的键。

于 2013-08-22T15:57:17.627 回答
1
var mensaplan = json['Mensaplan'];
for (key in mensaplan) {
     values = mensaplan[key];
     //do something with the values
}
于 2013-08-22T15:57:00.207 回答
0

这里不需要jquery,一个简单的for in 就足够了,但是你必须检查hasOwnProperty 函数,因为for in 循环也可以检索对象的方法。

for (var key in Mensaplan) {
    if (Mensaplan.hasOwnProperty(key) {
        console.log(Mensaplan[key]);
    }
}

更新:在您的情况下,Mensaplan 是一个包含在 json 中的数组...对于数组,最快的方法是标准 for 循环,而不是 for in

for (var i = 0, length = Mensaplan.length; i < length; i++) {
    console.log(Mensaplan[i]);
}
于 2013-08-22T15:57:24.557 回答