React throws error uncaught (in promise) syntaxerror: unexpected token < in json at position 0, when it is not able to find the JSON file.
But why this happens? Because you must have checked the location of JSON and it’s right there. Then why it could not find it?
First of all, this error occurs when you are trying to load JSON file using fetch
. But when you fetch something, you are loading from server. This could be a localhost or ip:port or domain name.
In our React projects we have 2 versions – Developer and Production. Their directory structure is also different. When we develop our application, we use developer directory structure. But for production we use build folder.
Suppose, you put your JSON file in src
folder, it won’t be accessible to fetch
api because that location doesn’t exist in server. You need to put the file in public
folder of your project. Now when you build the project, the file will automatically be included in build
production folder.
Solution
- Create JSON file.
- Put it into
public
folder. - Access it using
fetch
API.
public/file.json
–
{ "name": "Steve Rogers", "hero": "Captain America", "weapon": "Shield", "suit": "Blue & White" }
App.js
–
import "./styles.css"; import React from "react"; export default function App() { const [jsonData, setJsonData] = React.useState({}); React.useEffect(() => { const fetchJSON = async () => { const response = await fetch("/file.json"); let json = await response.json(); setJsonData(json); }; fetchJSON(); }, []); return ( <div> <p> This json is fetched from <b>file.json</b> </p> <p>Location of file.json - public/file.json</p> <pre>{JSON.stringify(jsonData, null, " ")}</pre> </div> ); }