Unexpected token By Dave Ceddia updated September 01, 2018
You made an HTTP request, probably with Fetch, and it blew up with this error. Or a very similar one.
Here’s what causes it and how to fix it.
Read on for a quick suggestion, and watch the video for a walkthrough of a few techniques you can try to debug this in your own app.
The Cause
This happens when you make a request to the server and parse the response as JSON, but it’s not JSON. The code responsible might look something like this:
The actual request worked fine. It got a response. But the res.json() is what failed.
JSON.parse
You might instead be parsing the JSON yourself with JSON.parse like this:
JSON.parse is what fetch’s res.json() is doing under the hood, so the error will be the same either way.
Valid JSON
JSON should start with a valid JSON value – an object, array, string, number, or false / true / null . This response started with a < (hence the “Unexpected token <”).
That unexpected token, < , is a strong clue that the response was HTML instead of JSON.
The root cause is that the server returned HTML or some other non-JSON string. Why would it do that?
“Unexpected token o in JSON at position 1” and other varieties
The exact text of this error will differ depending on what the server returned. The token and the position may vary, but the root cause is the same: the text that your app is trying to parse as JSON is not actually valid JSON.
Here are some other variations I’ve seen…
- Unexpected token < in JSON at position 1
- Unexpected token p in JSON at position 0
- Unexpected token d in JSON at position 0
Watch the video above for how this error works, and how to use your browser’s developer tools to figure out exactly what’s causing it. (or keep on readin’)
The Fix
The first thing to do is try logging it out. With fetch, you can use res.text() instead of res.json() to get the text string itself. Alter your code to read something like this, and check the console to see what’s causing the problem:
Note that these res.json() and res.text() functions are asynchronous, so you cannot log their return value directly. That’s why the console.log must be in a separate .then block.
Fix JSON.parse Unexpected Token
If you’re using JSON.parse directly, that’s a plain old synchronous call and you can replace the call with a console.log to see what’s going on.
Blame the Server?
The server might return HTML instead of JSON for a bunch of reasons:
- The URL doesn’t exist and the server returned an 404 page as HTML. You might have a typo in the client code ( /users instead of /user ) or in the server code that sets up the route.
- The server might need a restart if you just added a URL to it. If you’re using an Express server for instance, and you just added a new app.get('/users', . ) route, but didn’t restart the server, then it doesn’t know about the new route yet.
- The client’s proxy isn’t set up: if you’re using a Webpack dev server like Create React App, you can set up a proxy to forward requests to a backend server.
- The API root URL is / : If you’re using a proxy through Webpack or Create React App, make sure your API route is not at the root level / . That’ll confuse the proxy and you’ll get back HTML instead of your API request. Instead, prefix the route with something like /api/ .
Also, check the browser devtools Network tab and look for the request that caused this error, and then look at the response that came back.
Is it a 404 page? (might be a missing route or a typo)
Is it the index.html page? (might be a missing route or a misconfigured proxy)
If everything looks fine, then restart your backend server and your frontend dev server, and see if the problem goes away.
Problem Solved?
Hopefully you’ve now gotten rid of the error. If not, leave a comment below with what you tried.
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.
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.
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:
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
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’) :
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:
If you are using JSON.parse() we can do this in a try/catch block as follows:
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.
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:
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:
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»
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.
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:
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)
- 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.
About the Author
G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.
My aim to share what I have learnt with you! (and to help me remember )
Unexpected token in JSON at position 0 error
This post aims to address the «Unexpected token in JSON at position 0» error message. We will look into the various possible causes of this message and suggest methods to rectify it.
Steps we’ll cover:
What is JSON?
JSON which stands for Javascript Object Notation can be said to be a lightweight format for storing and transporting data, it is used often when data is sent from a server to a webpage.
If you have ever utilized API endpoints in your projects before, there’s a very high chance that JSON is being used to store and transport data between your web page and servers.
Let us quickly examine the utilization of JSON for transporting and storing data. We don’t need to look too far since the local storage on our internet browsers can function as servers.
The codeblock below shows how JSON can be used to transport data between local storage and the web page:
Exit fullscreen mode
Now that we are aware of what JSON is and how it can be applied, let us move on to resolving the «Unexpected token in JSON at position 0» error message.
What does the «Unexpected token < in JSON at position 0» error mean?
In very simple language, «Unexpected token < in JSON at position 0» indicates that you are parsing something else that is not JSON as JSON.
To prove my point, I will attempt to reproduce the mistake. Go to your browser console and execute this code snippet:
Exit fullscreen mode
The code snippet above will produce this type of error:
Why? because «undefined» is not JSON but we have tried to parse it as JSON.
There’s something I would like you to note before we proceed:
The actual «Unexpected token in JSON at position 0» message may vary depending on what your server generates, however, the fundamental reason remains the same: you are attempting to parse something that is not JSON as JSON.
Below are some of the different forms in which the error message could be presented:
» is not a valid JSON at JSON.parse».
Unexpected token ‘<‘, «<!DOCTYPE «. is not valid JSON.
Unexpected token ‘o’, «not found!» is not valid JSON.
Unexpected token ‘o’, «[object obj. is not valid JSON»
and so on. So going forward I’ll be using the general name «JSON.parse unexpected token» to refer to this error.
Now that we know what the «JSON.parse unexpected token» error means, let us proceed to know the different reasons why you might have this error and also look into ways to fix them.
Different Reasons Why You Might Have This Error and Their Fixes.
In this section of this article, 4 reasons and their fixes will be listed:
Hitting Any API endpoint that does not exist:
This is one of the most common causes of this error, and this tends to occur during the fetch request in javascript.
As you might have already assumed, yes! it occurs when you’re trying to parse an endpoint result that is not JSON as JSON.
In this part of the article, we will consider two brief cases — one to obtain a valid endpoint and show the outcome, and the other to retrieve an endpoint that doesn’t exist so we can reproduce the error message.
Example 1:
In this example, I’ve used the JSON endpoints from https://dummyjson.com/, a place where you can get fake JSON data to use during development.
I’ve picked a valid endpoint from this site and went ahead to call the javascript fetch method on it, check out the code snippet and its result below:
Exit fullscreen mode
Using the code snippet above, I want to clarify that JSON.parse() is being done by res.json() under the hood.
The image above shows that we got a valid JSON response, now let us move to the second example.
Example 2:
Exit fullscreen mode
https://dummyjson.com/myProduct/1 that has been used as our API is an endpoint that I made up, so it is not a valid API endpoint and as you know parsing it will be you trying to parse something that isn’t JSON, as it is not a formatted JSON.
How To Fix.
Make sure you are using a valid API endpoint:
To make sure you are using a valid JSON endpoint, use JSONFORMATTER to verify your endpoints before using it.
Always use the try-and-catch within your fetch method or function to prevent your app from crashing.
Spelling Error
This is so much similar to hitting the wrong API, only that you might have been pretty sure that the API endpoint exists.
Spelling error tends to happen due to typographical error or maybe you don’t know what the correct spellings are.
Spelling errors do not apply only to API endpoints, they can also occur while attempting to fetch information from your local storage and lead to the «JSON.parse unexpected token» error message showing up.
How To Fix.
Check and proofread well before hitting the API.
Make sure you verify your API before hitting it. use JSONFORMATTER.
Use the try-and-catch method in your function to prevent your app from crashing.
Building a side project?
Meet the headless, React-based solution to build sleek CRUD applications. With refine, you can build complex projects without having advanced frontend skills.
Try refine to rapidly build your next CRUD project, whether it’s an admin panel, dashboard, internal tool or storefront.
Forgetting to stringify your object:
If we don’t use the JSON.stringify() technique to convert our object into a string before sending it to a server, then we may encounter the error «JSON.parse unexpected token». This raises the question, «why is it necessary to transform our object into a string before sending it to a server?»
When sending data to a web server, the data has to be a string and to convert a javascript object to a string JSON.stringify() does the trick.
We are going to take two quick examples in this section, example 1 will represent the problem and example 2 will be the solution.
Example 1
Note:
Local storage will stand as our servers in this example.
I have a list of todos that I have written on my web page, I wish for them to stay even after I have reloaded my page*,* how do I make that happen?
I have to send those lists as data to my server, and then to retrieve them whenever I reload the page.
Exit fullscreen mode
In the code snippet that I have provided, I have sent my data to the server without converting the object to a string using JSON.stringify() . Let’s take a look at the consequence this will have on our page, below is the code snippet for retrieving the list, and an image of the result:
Exit fullscreen mode
The error indicates that I’m trying to parse an object, and it’s not a valid JSON.
Example 2(The fix):
All we have to do to fix this error is to stringify our list before sending it to the server:
Exit fullscreen mode
The code snippet above will fix the error.
In general, it is always a good idea to carefully check your JSON data for any syntax errors before attempting to parse it. This will help to ensure that your code is able to properly handle the JSON data and avoid any errors like the «Unexpected token in JSON at position 0» error.
Troubleshoot 'Uncaught SyntaxError: Unexpected token u in JSON at position 0'
The ‘Uncaught SyntaxError: Unexpected token u in JSON at position 0’ error is caused when the client has been asked to execute JSON.parse() on a string beginning with u instead of the stringified object it was expecting. Usually this is a stringified version of the undefined primitive.
The most likely underlying cause is that server-side code that normally generates and returns the stringified JSON malfunctioned. There are many reasons for this, but you should start by examining the server-side code and checking, for example, what inputs it is receiving, how it generates the object and stringifies it, and when it is being called to send a response to the client.
It is important to keep in mind that the error itself is a generic JavaScript runtime error. However, in the context of NetSuite and SuiteCommerce, it is usually because you have written a function within a service or service controller that fetches record data, and that function has then malfunctioned and sent back an unset variable.
Error Message
Let’s start with how it looks. You may get the following error either in your web developer console, or, more likely, in NetSuite via the SSP application execution log:
JSON.parse() is designed to be used in conjunction with JSON.stringify to send objects converted to strings between client and server. Parsing is a transformation process by the recipient to convert the string to an object. “Position 0” refers to the first character in the string, which should be an opening curly brace ( < ); if it is not this character, it will immediately halt parsing and throw an exception.
Issue
Typically this occurs when you are working on a service file, where you are connecting to NetSuite and then requesting some data. When dealing with transmissions to and from the web store, data is usually in the form of an object. At various stages this data will be stringified (ie converted from an object to a string) or parsed (converted from a string to an object) and this will be where this error surfaces.
If you attempt to parse something other than an object, the JavaScript processor will usually fail. As it’s expecting an object, it will stop at the exact point where it is failing, which is why it’ll return the position where it got stuck. An unexpected token simply means that it was expecting data, but instead got a command keyword (but this error can be triggered by things like strings too because of how they’re being told to be used).
If the unexpected token is a u and it is position 0 (ie the first character) then that means it tried to parse something that begins with a u. And what familiar keyword in JavaScript begins with a u?
In other words, if you got the error message in the title of this post then the chances are you’ve told the JavaScript processor to run the following:
Try this out in your browser’s developer console to see what I mean.
Resolving the Issue
So, we know what’s happening. But why is it happening? Let’s look at some of the possible causes.
Returning undefined
Now, you probably haven’t told it to explicitly return undefined so that it can then attempt to parse it (why would you?) but the likelihood is that you have told your model, service or service controller to return a value to the frontend of your site but that value has not been successfully passed. You’ve done something like, «Return the value of variable foo» but have messed it up.
To check this, inspect (or log!) what you’re returning:
- Is it an object?
- Does it have properties and have you called one that actually exists?
- Do those properties have values?
- Are there typos in your code, such as a misspelled name?
To illustrate this idea, see that trying to parse an object property that you have not defined will also return this error. For example:
If your code looks good, keep in mind that this could also happen if you’ve returned a variable before its value (an object) has been generated. In these cases, make sure any required operations have finished. For example, if your object will be generated after a promise has resolved, make sure it has been resolved before it is passed back. If the promise is failing, make sure it is set up to return an object that contains an error message!
Remember, if you’re going to try and log an object to the SSP application log, you will need to stringify it first, otherwise you will just get [object Object] in the log.
Trying to Parse a String
The error message can also occur if you’ve passed back a string that the application then tries to parse as if it were an object. Consider an example where you try to parse a string that begins with the letter u:
Related Errors
There are a couple of other errors that look similar to this one.
Attempting to Parse Unstringified Data
Another important thing to keep in mind is that before JSON can be parsed it must first be stringified. Now, modern service controllers are set up to detect when ‘complex’ data is being sent, so it will automatically try to stringify an array or object that is being sent back. For whatever reason, this may not be happening so you will need to track down the specific part in your code and see what’s going on.
Alternatively, you may be used to using service controllers and not realizing that you need to do this operation manually if you’re writing a custom .ss file, or if you’re writing something like a Suitelet.
In other words, you may have sent your object back well-formed and correct, but it’s not been stringified first, and the receiving part of the application has been told to parse the response. If it gets an unstringified object back, and it tries to parse it, it will fail.
To illustrate this, consider this example:
Trying to Parse an HTML Document
In some cases, a full HTML error page is generated and that is sent back instead of the desired value. When this happens, you’ll see something like this:
There is usually a very specific reason why this happened, that depends on your circumstances. Generally speaking, however: you’ve tried to request something, the server has failed, and, rather than return an object, it’s generated a full HTML error page and sent that back. The reason why there’s a < character at the start is because it’s always the first character in a HTML page’s source. In most cases, it will be <!DOCTYPE html> .
Therefore, if you want to troubleshoot this error, take a look at your browser’s Network tab in the developer tools and see what page it is sending back to you. It will usually have an error message in the body of the HTML.
Bonus Tip: Using JSON Methods to Copy an Object
Finally, a fun tip that relates to JSON.parse() and JSON.stringify() : if you’ve ever wanted to deep copy an object such that an object’s values are copied across to a new object by value rather than by reference, you can use JSON.parse(JSON.stringify(obj)) , where obj is your object.
For the record, you should use our built-in _.deepCopy() method in almost all cases because we account for certain situations where deeply copying an object can be problematic (such as with a Backbone model).
Anyway, what stringifying and immediately parsing does is convert the object to a string, thereby converting the properties and resolved values of the entire object to a string (and therefore terminating their pointers’ connections) and then converts it back to an object that you can use. This can be super helpful when you want to create a copy of an object as it is in that point in time:
From a performance perspective, it’s actually pretty quick, and it certainly saves you the hassle of writing a loop.