SyntaxError: Unexpected token < in JSON at position 0
errors indicate that an HTTP request expected a JSON response, but received non-JSON data instead.This article covers troubleshooting guidance for SyntaxError: Unexpected token < in JSON at position 0
errors, and these common variants:
SyntaxError: The string did not match the expected pattern
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
JSON Parse error: Unrecognized token '<'
This error occurs when a request expects a JSON response, but the actual response is in a different format. The JSON parser throws an error when it detects an invalid response.
Possible root causes for this error include:
Content-Type
header is not set to application/json
In many cases, the unexpected response is HTML or XML containing details of a server-side error.
Add error handling code and log the error and response data to the console to investigate why valid JSON wasn’t received. How the data is logged depends on if the code uses fetch()
or JSON.parse()
.
Common root causes and their solutions include:
fetch()
is correct.fetch()
A JavaScript fetch()
function may look similar to this:
The error occurs when response.json()
is called and the data can’t be parsed into JSON. For example, the response might be HTML or XML.
Print the data to the console by creating a clone of the response and adding a function to handle the error:
A response
object can only be read once. Therefore, we want to make a clone of it to print to the console before the original response is read on Line 5.
On Line 8, we added an error handling function. If response.json()
fails, this function is called and logs the error and responseClone
data to the console for further examination.
JSON.parse()
If the code uses JSON.parse(data)
, log the response data to the console by adding a try…catch
statement to handle the error: