2

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 ?

5
  • 2
    load your file seperately, take it into a variable, and then stringify it? Commented Jul 18, 2016 at 12:49
  • @Satej S That would give me a string, not an object ? Commented Jul 18, 2016 at 12:51
  • Where have you read that JSON.stringify loads a file? Commented Jul 18, 2016 at 12:51
  • @Vohuman think I misred it Commented Jul 18, 2016 at 12:53
  • Can you add the JSON you are trying to read to your question? Commented Jul 18, 2016 at 12:54

4 Answers 4

3

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

What should I do if I want json file to set among js tags on HTML between <script></script> tags?
2

If you are using jQuery:

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

Comments

2

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)
})

Comments

2

In case it helps anyone, just use this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.