46

How can I read local JSON file with fetch function in javascript? I have JSON file with some dump data and one function which read JSON file on server. For example :

readJson () {
   console.log(this)
   let vm = this
   // http://localhost:8080
   fetch('/Reading/api/file').then((response) => response.json()).then(json => {
       vm.users = json
       console.log(vm.users)
   }).catch(function () {
       vm.dataError = true
   })
}

So, What must to do to read local json file in this fetch function?

1
  • 5
    Side note: Your fetch call is missing a check on response.ok; this is such a common error I wrote up a blog post about it. Aug 15, 2018 at 13:13

3 Answers 3

44

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:

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.

4
  • 1
    The example makes it look like it's being served at http://localhost:8080/Reading/api/file, so I'm not sure this answer is applicable.
    – zzzzBov
    Aug 15, 2018 at 13:13
  • 1
    @zzzzBov - I totally missed that comment in the source, thanks. But it sound slike the OP may be hosting the page there, but trying to read a local file, not a file on the server. Aug 15, 2018 at 13:14
  • Yea, it's certainly ambiguous. I have a hunch that this is a dupe of "How do I return the response from an asynchronous call?".
    – zzzzBov
    Aug 15, 2018 at 13:15
  • @zzzzBov - Could well be. I've fixed the answer, thanks again. Aug 15, 2018 at 13:17
20

There is the very simple Fetch API:

you use it simply by:

// Replace ./data.json with your JSON feed
fetch('./data.json').then(response => {
  return response.json();
}).then(data => {
  // Work with JSON data here
  console.log(data);
}).catch(err => {
  // Do something for an error here
});
6
  • 2
    Which is what they're doing, including the fact you're missing the .ok check just like the OP is. Aug 15, 2018 at 13:14
  • they do not return the respone.json();
    – Barr J
    Aug 15, 2018 at 13:15
  • 4
    Yes, they do. They're using a concise arrow function. That has an implicit return. Aug 15, 2018 at 13:18
  • I want to read json file locally, or if I have to say exactly, must have a properties which say if propertie = true , then load local json file(with dump data) else load json data from tomcat server
    – BRRusev
    Aug 17, 2018 at 11:12
  • I did it by forming url as explicitly localhost:3000/<path-inside-public-folder>. Worked!
    – khanna
    Jul 1, 2020 at 5:36
0

I don't know why but fetching local jsons using fetch().then() doesn't work. Creating an async function and fetching that wat doesn't work neither.

The only way I made it is like this:

// dataList.json
[
  { "id": 1, "name": "Item 1" },
  { "id": 2, "name": "Item 2" },
  { "id": 3, "name": "Item 3" },
  { "id": 4, "name": "Item 4" }
]

// react component
import React, { useState } from 'react';
import jsonList from '../dataList.json'; // here I bring my jsonn file

export const App = () => {

    const [items, setItems] = useState(jsonList);

    console.log(items); // check that I have my array sored in my state

    return (
      <div>
        <h1>Workin with json</h1>
        {/*here I can, for example, map my state*/}
        {items.map((item) => {
          <div>
            <p>ID: {item.id}</p>
            <p>NAME: {item.name} </p>
          </div>;
        })}
      </div>
    );
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.