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.
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.
Share Improve this question asked Apr 5, 2017 at 10:43 LowderLowder 351 gold badge1 silver badge7 bronze badges 2- you could use filter method – user93 Commented Apr 5, 2017 at 10:43
- 1 Ohh really and your school teacher gave you this in homework. – Panther Commented Apr 5, 2017 at 10:45
3 Answers
Reset to default 2After 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./yakubixi/4/edit?html,css,js,output