开发者

Parse JSON with jQuery

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);
  开发者_如何学JAVA });

But that simply lists every value. How can I


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜