How to read JSON file with fetch() in javascript?

How can I read local JSON file with fetch function in javascript?

If you’re trying to read http://localhost:8080/Reading/api/file

…then what you’re doing is correct except you’re missing the .ok check (this is such a common mistake I’ve written a blog post about it). Also, since you’re using arrow functions, you don’t need to do let vm = this; unless you prefer it; arrow functions close over this. So:

readJson () {
   // http://localhost:8080
   fetch('/Reading/api/file')
   .then(response => {
       if (!response.ok) {
           throw new Error("HTTP error " + response.status);
       }
       return response.json();
   })
   .then(json => {
       this.users = json;
       //console.log(this.users);
   })
   .catch(function () {
       this.dataError = true;
   })
}

It’s important to remember that this is asynchronous; readJson returns before this.users has the value; it will get it later. If you want to know when it gets it, return the promise so calling code can use then on it:

readJson () {
   // http://localhost:8080
   return fetch('/Reading/api/file')
   // ...

More in the answers to these questions:

  • How do I return the response from an asynchronous call?
  • Why is my variable unaltered after I modify it inside of a function? – Asynchronous code reference

If you’re trying to read /Reading/api/file from the file system

…then you can’t, in at least some browsers, unless you serve the file via a web server process (as you appear to be serving the page. Then you read it via a URL on that server process as shown above.

To read a local file otherwise, the user has to identify the file, either by picking it in an input type="file" or dragging it into a dropzone. Then you’d read it via the File API, not fetch.

Leave a Comment