Fetching json data from local in react

I could just simply import “./city.json” in my react component. But I want to know why fetch is causing SyntaxError like “SyntaxError: Unexpected token < in JSON at position 0”.

my react code,

  componentDidMount(){
    fetch("./city.json")
      .then( response => response.json())
      .then( data => console.log(data))
      .catch(err=> console.log(err))
  }

./city.json file,

{
   "city":[
      {
         "id":"5368361",
         "name":"Los Angeles",
         "country":"US",
         "admin1":"California",
         "lat":"34.0522300",
         "lon":"-118.2436800",
         "pop":"3971883"
      }
   ]
}

Answer

Fetch is most commonly used for fetching resources across the network. The API depends on receiving a Response object. You cannot simply just fetch a raw file. The syntax will not be what Fetch is expecting.

In theory, you could have a function that requires the json, and send it in the body of a Response, so fetch can parse the response. But really, you should probably just import or require the JSON if it is a local file.

If the file is available via a web server (for example, if you’re running localhost:8080) check if you can retrieve the json by browsing http://localhost:8080/city.json. If this returns a 200 response with the JSON in the body of the response, then the fetch you have looks good.

Leave a Reply

Your email address will not be published. Required fields are marked *