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.

sao
  • 1,835
  • 6
  • 21
  • 40
  • 3
    Possible duplicate of [How to read an external local JSON file in JavaScript?](https://stackoverflow.com/questions/19706046/how-to-read-an-external-local-json-file-in-javascript) – Ayush Gupta Oct 09 '19 at 12:00
  • You might need ajax call to read file – Jaydip Jadhav Oct 09 '19 at 12:00
  • forgot to mention, I cannot use jquery –  Oct 09 '19 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. – ghchoi Oct 09 '19 at 12:03

2 Answers2

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();
}
yourdaddy
  • 11
  • 2
0

Use window.fetch:

fetch('data.json')
  .then(body => body.json())
  .then(data => {
    //do stuff with data
  });
Sandro
  • 1,051
  • 7
  • 15
  • I am getting this error: Fetch API cannot load URL scheme must be "http" or "https" for CORS request. –  Oct 09 '19 at 12:03
  • @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')` – Sandro Oct 09 '19 at 12:04
  • it is just a local file near the js file –  Oct 09 '19 at 12:07
  • 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`. – Sandro Oct 09 '19 at 12:10
  • file protocol has different restrictions than http[s], run a local server – epascarello Oct 09 '19 at 12:13
  • If you run a local server you can also serve the JSON file with it. – Sandro Oct 09 '19 at 12:18