Derek
Derek

Reputation: 8630

Iterate JSON Response with Javascript / JQuery

I have the following JSON response that i am trying to iterate with Javascript :-

{
    "DocumentResponseResults": [
        {
            "Name": "Example1",
            "Id": "1"
        },
        {
            "Name": "Example2",
            "Id": "2"
        },
        {
            "Name": "Example3",
            "Id": "3"
        }
    ]
}

I've tested to makes sure its valid JSON using an online validator.

I'm receiving this via a response from a WebMethod in asp.net.

In the response it looks like this:-

d:"{"DocumentResponseResults":[{"Name":"Example1","Id":"1"},{"Name":"Example2","Id":"2"},{"Name":"Example3","Id":"3"}]}"

I'm trying to iterate the items in the JSON string.

I started off by parsing it like this :-

var jsonData = JSON.parse(response.d);

I've tried to iterate the array of objects by accessing the Items collection, but javascript informs me that the items property is undefined.

Can anyone advise how i iterate the collection, and pull out properties such as "Name" & "Id"

Upvotes: 0

Views: 2557

Answers (5)

roger.vila
roger.vila

Reputation: 168

you can access the array this way:

DocumentResponseResults[i].Name

DocumentResponseResults[i].Id

where 'i' is a number.

if you want to go through the array, you can use jQuery.each()

http://api.jquery.com/jquery.each/

or just a for() loop.

Upvotes: 1

user3227295
user3227295

Reputation: 2156

jsonData.DocumentResponseResults is the items property.

Upvotes: 0

Sunil B N
Sunil B N

Reputation: 4225

var items = response.DocumentResponseResults //gets you array
for (var i = 0; i < items .length; i++) { 
    var name = items[i].Name;
    var id = items[i].Id;
    console.log("Name:"+name + " Id:"+id+"\n");
}

Upvotes: 2

Moppo
Moppo

Reputation: 19275

$.each( jsonData.DocumentResponseResults , function( k, v )
{
    //here you can access v.Name, v.Id etc.                

});

Upvotes: 1

Petr Bela
Petr Bela

Reputation: 8741

jsonData.DocumentResponseResults.forEach(function(Result) {
  console.log(Result.Name)
});

Upvotes: 4

Related Questions