使用jQuery解析JSON

我试图用jQuery解析以下JSON并获取每个id值。 任何人都可以建议吗?

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

]

到目前为止我有:

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

但这只列出了每一个价值。 我怎么能够

这将列出数组中的每个对象,以获取您所在的对象的id属性,只需添加.id如下所示:

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

如果test是包含JSON的字符串,则可以使用jQuery.parseJSON解析它,它将返回一个JavaScript对象。

如果test是这样写的:

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

…它已经一个JavaScript对象; 特别是一个数组。 jQuery.each将遍历每个数组条目。 如果您想循环遍历这些条目的属性,可以使用第二个循环:

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

实例