Skip to content
javascript

How to fix "SyntaxError: Unexpected token < in JSON at position 0" and "Unexpected end of JSON input"

Apr 1, 2023Abhishek EH3 Min Read
How to fix "SyntaxError: Unexpected token < in JSON at position 0" and "Unexpected end of JSON input"

If you are coding in JavaScript, React, or any other JavaScript library/framework, you would have come across the following errors:

SyntaxError: Unexpected token < in JSON at position 0

SyntaxError: Unexpected end of JSON input

When does this error occur?

This error occurs when you are trying to parse a string to JSON and the string is not parsable. In other words, it happens when you pass an invalid JSON string to JSON.parse() function.

Try executing the following code in the browser console:

1JSON.parse("<html>")

You will see the following error:

json parse error 1

So the error is telling that it is seeing a string < at the beginning since a valid JSON should start with {.

Now if you execute the following code, you will get the second error:

1JSON.parse('{"html')
json parse error 2

If you observe the JSON string, it starts as a valid JSON, however, the JSON is not complete. Hence it is telling 'unexpected end of JSON input'.

Let's now see how we can reproduce same issue in React application:

App.js
1import { useEffect } from "react"
2
3function App() {
4 useEffect(() => {
5 const fetchData = async () => {
6 const response = await fetch("https://jsonplaceholder.typicode.com/")
7 const data = await response.json()
8 console.log({ data })
9 }
10
11 fetchData()
12 }, [])
13 return <div className="App">home</div>
14}
15
16export default App

The above code attempts to fetch the data from https://jsonplaceholder.typicode.com/ and calls response.json(). When we call response.json(), it internally calls JSON.parse() to convert the response into a JSON Object.

However, the URL we have passed is of an HTML page and we will be getting an HTML string as the response. Hence, if you execute the above code, it will throw the error: SyntaxError: Unexpected token < in JSON at position 0.

How to fix this issue?

We can fix this issue by making sure that we are calling the right endpoint and we are getting a valid JSON response.

We can do so by opening the URL in the browser and checking the content-type response header:

HTML content type

html content type

JSON content type

If you check the content-type of an endpoint that returns a valid JSON, like https://jsonplaceholder.typicode.com/posts, you will see the content-type as application/json.

json content type

You could also validate if a string is a valid JSON or not in tools like JSON Formatter.

Do follow me on twitter where I post developer insights more often!

© 2024 CodingDeft.Com