1

I am trying to parse the following JSON with jQuery and get each id value. Can anyone advise?

[
{
    "id": "1",
    "name": "Boat"
},
{
    "id": "2",
    "name": "Cable"
}

]

So far I have:

$.each(test, function(i,item){
   alert(item);
   });

But that simply lists every value. How can I

2 Answers 2

2

That'll list every object in your array, to get the id property of the one you're on, just add .id like this:

$.each(test, function(i,item){
  alert(item.id);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Nick, yes you are correct. Otherwise I would have to test for if(innerKey == 'id'). Best regards, Ben.
1

If test is a string containing JSON, you can parse it with jQuery.parseJSON, which will return a JavaScript object.

If test is written like this:

var test = [
    {
        "id": "1",
        "name": "Boat"
    },
    {
        "id": "2",
        "name": "Cable"
    }
];

...it already is a JavaScript object; specifically an array. jQuery.each will loop through each array entry. If you want to loop through the properties of those entries as well, you can use a second loop:

$.each(test, function(outerKey, outerValue) {
    // At this level, outerKey is the key (index, mostly) in the
    // outer array, so 0 or 1 in your case. outerValue is the
    // object assigned to that array entry.
    $.each(outerValue, function(innerKey, innerValue) {
        // At this level, innerKey is the property name in the object,
        // and innerValue is the property's value
    });
});

Live example

1 Comment

Superb! Thank you. I was missing the jQuery.parseJSON and hence trying to itterate through a string! Best regards, Ben.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.