oshirowanen
oshirowanen

Reputation: 15965

Extracting required parts from JSON data?

I am currently getting the following data back from the server:

{
    "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
        }
    ]
}

I know how to display the first Group value using jQuery:

$.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) ;
    }
});

How do I display all the values in Group and Count? For example:

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

Upvotes: 0

Views: 138

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

You can loop over the conflicts.d array:

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

Upvotes: 1

Grim...
Grim...

Reputation: 16953

You probably want to look into $.each : http://jqapi.com/#p=jQuery.each

Upvotes: 0

Related Questions