Im having some issues when trying to get some Json data into a specific format.
I basically need this Json data:
{
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"
}
]
To go into this javascript array:
var arrProducts = [
title: "{{ product.title }}",
url: "{{ product.url }}",
label: "{{ product.title }}",
magazine: "{{ product.magazine }}",
image: "{{ product.imageThumb }}",
newsstand: "{{ product.newsstand }}",
kindle: "{{ product.kindle }}",
barnesnoble: "{{ product.barnesnoble }}",
zinio: "{{ product.zinio }}",
kobo: "{{ product.kobo }}",
waterstones: "{{ product.waterstones }}",
type: "{{ product.type }}",
},
];
I have tried using:
var allProducts = $.get("http://localhost:8888/web/app_dev.php/api/v1/search/search.json, function(data) {
var productsArray = data.products;
console.log(productsArray);
});
But that method does not build the array in the format I require. Console.log outputs a bunch of objects. Maybe an for each loop could be a solution? – Any help is appreciated, my Javascript isnt that great!
use http://jsonlint.com to validate your json. If it won’t pass there, it won’t pass through ajax either. Your sample is missing double quotes on object keys and a starting brace and has extra comma and your file shoudn’t include
var arrProducts =when consumed by ajaxThere is a difference however if you place a script tag with this file in page during initial page load. Then the
var arrProducts =is needed and the quotes on object keys are not. Then rather than ajax you would simply loop over the variablearrProductsEDit:
To loop over first sample
There is a wealth of information available about how to parse json and loop over objects and arrays … did you try searching?