从JSON数据中提取所需的部分?

时间:2012-02-06 14:49:04

标签: json jquery jsonp

我目前正在从服务器获取以下数据:

{
    "d": [
        {
            "__type": "Conflict",
            "Group": "Clients",
            "Count": 284
        },
        {
            "__type": "Conflict",
            "Group": "Addresses",
            "Count": 127
        },
        {
            "__type": "Conflict",
            "Group": "Matters",
            "Count": 287
        },
        {
            "__type": "Conflict",
            "Group": "Individuals",
            "Count": 500
        },
        {
            "__type": "Conflict",
            "Group": "Organisations",
            "Count": 107
        }
    ]
}

我知道如何使用jQuery显示第一个Group值:

$.ajax({
    type: 'POST',
    url: 'conflict.asmx/GetConflicts',
    data: '{phrase: "john"}',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function( conflicts ) {
        if( conflicts.d[0] ) {
             alert( conflicts.d[0].Group ) ;
        } else {
            alert ( "null" );
        }
    },
    error: function(xhr, status, error) {
             var err = eval("(" + xhr.responseText + ")");
             alert(err.Message) ;
    }
});

如何在GroupCount中显示所有值?例如:

Clients: 284
Addresses: 127
Matters: 287
Individuals: 500
Organisations: 107

2 个答案:

答案 0 :(得分:1)

您可以遍历conflicts.d数组:

success: function( conflicts ) {
    if( conflicts.d ) {
        $.each(conflicts.d, function(index, conflict) {
            alert(conflict.Group + ':' + conflict.Count);
        });
    } else {
        alert ( "null" );
    }
}

答案 1 :(得分:0)

您可能希望查看$.eachhttp://jqapi.com/#p=jQuery.each