TanguyB
TanguyB

Reputation: 2006

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 ?

Upvotes: 2

Views: 11582

Answers (4)

Andy Lorenz
Andy Lorenz

Reputation: 3084

In case it helps anyone, just use this:

const dataObjectFromFile = require('./path/to/datafile.json');

Upvotes: 2

charlietfl
charlietfl

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

Arun Ghosh
Arun Ghosh

Reputation: 7734

If you are using jQuery:

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

Upvotes: 2

Rory McCrossan
Rory McCrossan

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

Related Questions