使用$ .each获取更复杂的JSON数据

时间:2011-10-13 10:12:18

标签: jquery

我了解如何使用$.each来查看如下所示的JSON数据:

{
    "one": "Singular sensation",
    "two": "Beady little eyes",
    "three": "Little birds pitch by my doorstep"
}

例如:

$.each(data, function(key, val) {
    echo '<div>' + val + '-' + key + '</div>';
});

但是如何使用$.each来查看看起来像这样的JSON数据:

{
    "d": [
        {
            "__type": "Tab",
            "id": 1,
            "name": "Innovation",
            "ordering": 0
        },
        {
            "__type": "Tab",
            "id": 3,
            "name": "Thought",
            "ordering": 0
        },
        {
            "__type": "Tab",
            "id": 0,
            "name": "Collaboration",
            "ordering": 0
        }
    ]
}

我想使用idname

4 个答案:

答案 0 :(得分:1)

使用此:

var complex_data = {
    "d": [
        {
            "__type": "Tab",
            "id": 1,
            "name": "Innovation",
            "ordering": 0
        },
         ...
    ]
}

//Use:
$.each(complex_data.d, function(i, val){
    //The following properties can be used in your code:
    val.id;
    val.name;
    //And also: val.__type, val.ordering
});

如果您的complex_data包含更多密钥,例如d,请使用:

$.each(complex_data, function(i, val){
    $.each(val, function(j, val){
        //The following properties can be used in your code:
        val.id;
        val.name;
        //Also: val.__type, val.ordering
    });
});

答案 1 :(得分:0)

同样的方式

$.each(data, function(key, val) {
    $.each(val, function(index, val2){
      console.log(val2.name);
    });
});

答案 2 :(得分:0)

$.each(data.d, function(index, val) {
    echo '<div>' + val.id + '-' + val.name + '</div>';
});

答案 3 :(得分:0)

这段代码对你的例子非常具体,所以可能需要稍微调整一下,但你可以这样做:

data = {
    "d": [
        {
            "__type": "Tab",
            "id": 1,
            "name": "Innovation",
            "ordering": 0
        },
        {
            "__type": "Tab",
            "id": 3,
            "name": "Thought",
            "ordering": 0
        },
        {
            "__type": "Tab",
            "id": 0,
            "name": "Collaboration",
            "ordering": 0
        }
    ]
}

$.each(data.d, function(key, val) {
    $('#data').append('id: ' + val.id + ', name: ' + val.name + '<br />');
});

http://jsfiddle.net/Uxguf/