1

I have a JSON file containing data that I want to read in Javascript instead of hard-coding them in code (more than 3000 lines).

I tried referencing JSON in HTML and using it but returned an empty array

In HTML:

<script type="file" src="data.json"></script>

In javascript:

console.log(JSON.parse(data))

I get back an empty array rather than the data.

4
  • 3
    Possible duplicate of How to read an external local JSON file in JavaScript? Commented Oct 9, 2019 at 12:00
  • You might need ajax call to read file Commented Oct 9, 2019 at 12:00
  • forgot to mention, I cannot use jquery Commented Oct 9, 2019 at 12:01
  • If you have a data.json file that starts with { or [ and respectively ends with }, ], simply add var data = in front of the file. And import the file as a script and just use it as a JS variable. Commented Oct 9, 2019 at 12:03

2 Answers 2

1
function readJSON(path) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', path, true);
    xhr.responseType = 'blob';
    xhr.onload = function(e) { 
      if (this.status == 200) {
          var file = new File([this.response], 'temp');
          var fileReader = new FileReader();
          fileReader.addEventListener('load', function(){
               //do stuff with fileReader.result
          });
          fileReader.readAsText(file);
      } 
    }
    xhr.send();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use window.fetch:

fetch('data.json')
  .then(body => body.json())
  .then(data => {
    //do stuff with data
  });

6 Comments

I am getting this error: Fetch API cannot load URL scheme must be "http" or "https" for CORS request.
@elcondores are you trying to load data from another domain? If so, just enter the full URL, e.g.: fetch('https://jsonplaceholder.typicode.com/todos/1')
it is just a local file near the js file
Try entering the full URL (so that if you open the URL on a browser the JSON file is displayed). Or try using a relative path, e.g.: ./data.json.
file protocol has different restrictions than http[s], run a local server
|