Reputation: 586
I am making an ajax call that returns some json data. I need to take this data, loop through it and build a new javascript array.
This is what the returned json looks like:
{
query: [ ],
products:
[
{
title: "title 1",
price: "6.00",
magazine: "magazine name 1",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link1.php"
},
{
title: "title 2",
price: "6.00",
magazine: "magazine name 2",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link2.php"
},
{
title: "title 3",
price: "6.00",
magazine: "magazine name 3",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link3.php"
}
]
}
How do I loop through this data in javascript? This is what I have so far but it is very wrong! - apologies my javascript is not my strongest skill!
var allProducts = $.get("http://localhost:8888/imagine-publishing/web/app_dev.php/api/v1/search/search.json?query=pho", function(data) {
var arrProducts = [
for (var product in allProducts) {
title = product.title,
url = product.url,
label = product.title,
magazine = product.magazine,
image = product.imageThumb,
newsstand = product.newsstand,
googleplay = product.googleplay,
kindle = product.kindle,
barnesnoble = product.barnesnoble,
zinio = product.zinio,
kobo = product.kobo,
waterstones = product.waterstones,
type = product.type,
brandurl = product.brandurl
},
];
});
console.log(arrProducts);
Upvotes: 0
Views: 210
Reputation: 1321
Using jQuery's getJSON
http://api.jquery.com/jQuery.getJSON/
$.getJSON(url, function(data){
// Your code goes here
});
Upvotes: 0
Reputation: 944528
Assuming the JSON is served with the correct Content-Type (application/json
), jQuery will automatically parse the JSON and populate the first argument of the callback function with the result.
var arrProducts = data.products;
Upvotes: 4
Reputation: 3917
http://api.jquery.com/jQuery.parseJSON/
jQuery.parseJSON("json string")
Upvotes: 1