Reputation: 2006
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 ?
Upvotes: 2
Views: 11582
Reputation: 3084
In case it helps anyone, just use this:
const dataObjectFromFile = require('./path/to/datafile.json');
Upvotes: 2
Reputation: 171669
JSON.stringify()
first argument needs to be a valid JSON string, not a file.
You need to use AJAX to retrieve file from server:
$.getJSON('./test.json', function(responseObject){
var obj = responseObject
console.log(obj)
})
Upvotes: 2
Reputation: 7734
If you are using jQuery:
$.getJSON( "/test.json", function( obj ) {
console.log(obj.details.ProductID);
});
Upvotes: 2
Reputation: 337560
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);
});
Upvotes: 3