How to fix SyntaxError Unexpected Token in JSON
Getting SyntaxError: Unexpected token < in JSON at position 0 when using fetch or JSON.parse. I will go over fixes for this!
Jan 18, 2023 | Read time 9 minutes🔔 Table of contents
Introduction
A common issue that I see when working with front-end JavaScript heavy apps is the dreaded “SyntaxError Unexpected Token in JSON” error! Now this error can be of the form:
SyntaxError: Unexpected token < in JSON at position 0
SyntaxError: Unexpected end of JSON input
syntaxerror: unexpected token '<', "<!doctype "... is not valid json
The error “SyntaxError Unexpected Token in JSON” appears when you try to parse content (for example - data from a database, api, etc), but the content itself is not JSON (could be XML, HTML, CSV) or invalid JSON containing unescaped characters, missing commas and brackets.
There are a few things you can try to fix this error:
-
Check that the content you are trying to parse is JSON format and not HTML or XML
-
Verify that there are no missing or extra commas.
-
Make sure to check for unescaped special characters.
-
Check for mismatched brackets or quotes.
-
Make sure the JSON is valid. You can use a tool like JSONLint to validate your JSON and check for any errors.
1. Check that the content you are trying to parse is JSON format and not HTML or XML
A common reason why the error “SyntaxError Unexpected Token in JSON” comes up is that we are trying to parse content that is not even JSON.
Consider the following front-end JavaScript code:
fetch('https://localhost:3000/data')
.then(response => response.json())
.then(data => {
console.log(data);
// Use the data here
})
In the above example, the fetch() function is being used to retrieve data from a API that returns JSON format - in this case https://localhost:3000/data.
The fetch()
function then returns a promise, and when that promise resolves, we handle that with the response.json()
method. This just takes our JSON response and converts it to a JSON object to be used!
After that we just console.log out the data object
Now for the server-side of things, look on to our Node JS route that returns the JSON /data
var http = require('http');
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'text/html'); ❌ Not returning JSON.
res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);
We can see that it is setting the Header as text/html
. This will give you the error:
syntaxerror: unexpected token '<', "<!doctype "... is not valid json
This is because we are trying to parse the content with JSON.parse()
or in our case response.json()
and receiving a HTML file!
To fix this, we just need to change the returned header to res.setHeader('Content-Type', 'application/json')
:
...
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'application/json'); ✔️ Returning JSON.
res.end(JSON.stringify({ a: 1 }));
});
...
Whats
Content-Type
request header anyway?Pretty much every resource on the internet will need to have a type (similar to how your file system contains file types like images, videos, text, etc). This is known as a MIME type (Multipurpose Internet Mail Extension)
Browsers need to know what content type a resource is so that it can best handle it. Most modern browsers are becoming good at figuring out which content type a resource is, but its not always 100% correct.
That is why still need to explicitly specify our request header
content-type
!
syntaxerror: unexpected token ‘<’, “<!doctype “… is not valid json
This error also comes up when your API is returning invalid error pages such as 404/500 HTML pages. Since HTML usually starts with a “less than” tag symbol (<
) and JSON is not valid with <
tags, it will through this error.
For example, when everything is working find, your node API will happily return JSON. However when it fails with a 500 internal error, it could return a custom HTML error page!
In this case, when you try to do JSON.parse(data)
you will get the syntaxerror: unexpected token '<', "<!doctype "... is not valid json
.
Additionally, check that you are calling the correct API url. As an example, lets say the API that returns JSON is using the /data
route. If you misspelt this, you could be redirected to a 404 HTML page instead!
Tip: Use appropriate error handlers for non-JSON data
If you are using fetch()
to retrieve your data, we can add a catch handler to give meaningful error messages to the user:
fetch('https://localhost:3000/data')
.then(response => response.json())
.then(data => {
console.log(data);
// Use the data here
})
.catch(error => console.error(error)); /*✔️ Friendly error message for debugging! */
If you are using JSON.parse()
we can do this in a try/catch block as follows:
try {
JSON.parse(data);
}
catch (error) {
console.log('Error parsing JSON:', error, data); /*✔️ Friendly message for debugging ! */
}
2. Verify that there are no missing or extra commas.
JSON objects and arrays should have a comma between each item, except for the last one.
{
"name": "John Smith"
"age": 30
"address": {
"street": "123 Main St"
"city": "Anytown"
"state": "USA"
}
}
This JSON object will throw a “syntaxerror unexpected token” error because there is no comma between “John Smith” and “age”, and also between “Anytown” and “state”.
To fix this, you would add commas as follows:
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
}
}
By adding commas between each item except for the last one, the JSON object is now in the correct format and should parse without error.
3. Make sure to use double quotes and escape special characters.
JSON strings must be wrapped in double quotes, and any special characters within the string must be properly escaped. Consider the following example:
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
},
"message": "It's a lovely day"
}
When we try to parse this with JSON.parse
, we will get the error: SyntaxError: Invalid or unexpected token.
The problem is with the following line using a apostrophe:
"message": "It's a lovely day"
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
},
"message": "It\'s a lovely day"
}
As we can see, this will fix our error since we escape the aspostrophe as such:
"message": "It\'s a lovely day"
4. Check for mismatched brackets or quotes.
Make sure all brackets and quotes are properly closed and match up.
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
}
In this example, the JSON object is missing a closing curly bracket, which indicates the end of the object. Because of this, it will throw a “syntaxerror unexpected token” error.
To fix this, you would add the missing closing curly bracket as follows:
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
}
}
5. Make sure the JSON is valid. You can use a tool like JSONLint to validate your JSON and check for any errors.
If you want to be sure that the JSON is valid, we can try to use the NPM package JSONLint (https://github.com/zaach/jsonlint)
We can install jsonlint with npm as follows:
- Open up the terminal
- Run NPM install
npm install jsonlint -g
- We can then validate a file like so:
jsonlint myfile.json
Summary
In this article I went over the SyntaxError: Unexpected token < in JSON at position 0 when dealing with parsing JSON with fetch
or JSON.parse
. This error is mainly due to the JSON not being in correct format or the content that we are trying to parse is not even JSON.
In the case of JSON being invalid, make sure to check for unescaped characters, missing commas, non-matching brackets and quotes.
To be really sure, check the JSON with tools like JSONLint to validate!
In the case of the content you are trying to parse being non-JSON such as HTML, check your API to make sure that error pages return JSON correctly instead of HTML pages.