0

I have a simple folder structure, such as:

project  
│
└───data
│     file.json
│    
└───js
      test.js

I wish to read the file.json in the test.js to do some other back-end stuff. Here is a similar (but generic) JSON file:

{"key1": 50, "key2": 6, "key3": 20,
"ke4": 18, "key5": 38, "key6": 30}

So far, i've tried:

var request = new XMLHttpRequest();
request.open("GET", "< path >", false);
request.send(null)
var my_JSON_object = JSON.parse(request.responseText);
alert(my_JSON_object.result[0]);

But it didn't yield results.

I've checked this post and this one. They ask similar question but they're quite old.

So, my question is: How does one do this and is there a new way (e.g. fetch) to do it?

MrCorote
  • 565
  • 8
  • 21

2 Answers2

1

Despite those answers being a little old, the obsolete code still works, answering the first half of your question. I wouldn't care about the deprecated code, as long as it works. I'm not sure how recent this basic implementation of jQuery is, but it works just like the other solutions:

 $.getJSON('data/file.json', function(data) {
     console.log(JSON.stringify(data));
 });

Also, from the code you gave in your example, it doesn't work because you are not implementing its asynchronous nature properly. Since it is an asynchronous operation, it needs to specify a callback function to execute after the file is loaded:

function readTextFile(file, callback) {
   var request = new XMLHttpRequest();
   request.overrideMimeType("application/json");
   request.open("GET", "< path >", false);
   request.onreadystatechange = function() {
       if (request.readyState === 4 && request.status == "200") {
          callback(request.responseText);
       }
   }
   request.send(null);
}

// Implementation:
readTextFile("data/file.json", function(text){
   var my_JSON_object = JSON.parse(text);
   console.log(my_JSON_object);
   alert(my_JSON_object.result[0]);
});
Max Voisard
  • 1,685
  • 1
  • 8
  • 18
0

I think the answer you provided should work well. Although, I think the file path might be wrong. Instead of :

$.getJSON('data/file.json', function(data) {
     console.log(JSON.stringify(data));
 });

Shouldn't it be:

$.getJSON('./data/file.json', function(data) {
     console.log(JSON.stringify(data));
 });

Note the "./" at the beginning of the file path.