TanguyB TanguyB - 4 months ago 8
JSON Question

Load a JSON file into a JS object

I try to load a json file into a JavaScript var but it just doesn't work out.

var jsonString = JSON.stringify('./test.json');
var obj = JSON.parse(jsonString);

console.log(obj.details.ProductID);


it says that it can't read property ProductID of undefined.

What am I doing wrong here ?

Answer

You need to make an AJAX call to get the file. $.getJSON was intended for exactly this purpose:

$.getJSON('./test.json', function(obj) {
    console.log(obj.details.ProductID);
});