I have this 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
}
}
I need to parse this json and get description of product by id.
After you parse json with JSON.parse()
you can use find method to find object with matching id and if object is found you can get its description.
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)
}
Try something like this using 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);
}
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