添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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

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:

JSON.parse("<html>")
    Enter fullscreen mode
    Exit fullscreen mode

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:

JSON.parse('{"html')
    Enter fullscreen mode
    Exit fullscreen mode

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:

import { useEffect } from "react"
function App() {
  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch("https://jsonplaceholder.typicode.com/")
      const data = await response.json()
      console.log({ data })
    fetchData()
  }, [])
  return <div className="App">home</div>
export default App
    Enter fullscreen mode
    Exit fullscreen mode

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.

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:

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community © 2016 - 2024.