2017-04-05 55 views
-3

我有这样的JSON:的Json查找阵列

{ 
"response":{ 
    "name":"Demo Shop", 
    "items":[ 
     { 
      "id":3, 
      "name":"first", 
      "cost":10, 
      "description":"First description" 
     }, 
     { 
      "id":2, 
      "name":"second", 
      "cost":50, 
      "description":"second description" 
     } 
    ], 
    "coupon":false 
} 
} 

我需要解析此JSON和ID获得产品的描述。

+0

您可以使用过滤方法 – user93

+0

喔真的和学校里的老师给你这个功课。 – Panther

回答

1

你解析与JSON.parse() JSON后,您可以用找到的方法来找到对象,具有匹配的ID,如果找到对象,你可以得到它的描述。

var json = '{"response":{"name":"Demo Shop","items":[{"id":3,"name":"first","cost":10,"description":"First description"},{"id":2,"name":"second","cost":50,"description":"second description"}],"coupon":false}}' 
 

 
var desc = JSON.parse(json).response.items.find(function(e) { 
 
    return e.id == 3 
 
}) 
 

 
if(desc) { 
 
    console.log(desc.description) 
 
}

0

使用filter尝试是这样的:

var json = { 
 
    "response":{ 
 
     "name":"Demo Shop", 
 
     "items":[ 
 
      { 
 
       "id":3, 
 
       "name":"first", 
 
       "cost":10, 
 
       "description":"First description" 
 
      }, 
 
      { 
 
       "id":2, 
 
       "name":"second", 
 
       "cost":50, 
 
       "description":"second description" 
 
      } 
 
     ], 
 
     "coupon":false 
 
    } 
 
} 
 

 
var result = json.response.items.filter(function(item) { 
 
    return item.id === 3; //Change 3 to what you want to search for 
 
}); 
 

 
if(result.length > 0) { 
 
    console.log(result[0].description); 
 
}

0
var json=[{"name":"Lenovo Thinkpad 41A4298","website":"google"}, 
{"name":"Lenovo Thinkpad 41A2222","website":"google"}, 
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"}, 
{"name":"Lenovo Thinkpad 41A424448","website":"google"}, 
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"}, 
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"}, 
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"}, 
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]; 


var as=$(json).filter(function (i,n){return n.website==='yahoo'}); 



for (var i=0;i<as.length;i++) 
    { 
    alert(as[i].name +"   "+as[i].website) 
} 

http://jsbin.com/yakubixi/4/edit?html,css,js,output