In a React app component which handles Facebook-like content feeds, I am running into an error:
Feed.js:94 undefined «parsererror» «SyntaxError: Unexpected token < in JSON at position 0
I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn’t seem to be the case here.
More confusingly, I rolled the code back to an earlier, known-working version and I’m still getting the error.
Feed.js:
import React from 'react';
var ThreadForm = React.createClass({
getInitialState: function () {
return {author: '',
text: '',
included: '',
victim: ''
}
},
handleAuthorChange: function (e) {
this.setState({author: e.target.value})
},
handleTextChange: function (e) {
this.setState({text: e.target.value})
},
handleIncludedChange: function (e) {
this.setState({included: e.target.value})
},
handleVictimChange: function (e) {
this.setState({victim: e.target.value})
},
handleSubmit: function (e) {
e.preventDefault()
var author = this.state.author.trim()
var text = this.state.text.trim()
var included = this.state.included.trim()
var victim = this.state.victim.trim()
if (!text || !author || !included || !victim) {
return
}
this.props.onThreadSubmit({author: author,
text: text,
included: included,
victim: victim
})
this.setState({author: '',
text: '',
included: '',
victim: ''
})
},
render: function () {
return (
<form className="threadForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange} />
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange} />
<input
type="text"
placeholder="Name your victim"
value={this.state.victim}
onChange={this.handleVictimChange} />
<input
type="text"
placeholder="Who can see?"
value={this.state.included}
onChange={this.handleIncludedChange} />
<input type="submit" value="Post" />
</form>
)
}
})
var ThreadsBox = React.createClass({
loadThreadsFromServer: function () {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
handleThreadSubmit: function (thread) {
var threads = this.state.data
var newThreads = threads.concat([thread])
this.setState({data: newThreads})
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: thread,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
this.setState({data: threads})
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
getInitialState: function () {
return {data: []}
},
componentDidMount: function () {
this.loadThreadsFromServer()
setInterval(this.loadThreadsFromServer, this.props.pollInterval)
},
render: function () {
return (
<div className="threadsBox">
<h1>Feed</h1>
<div>
<ThreadForm onThreadSubmit={this.handleThreadSubmit} />
</div>
</div>
)
}
})
module.exports = ThreadsBox
In Chrome developer tools, the error seems to be coming from this function:
loadThreadsFromServer: function loadThreadsFromServer() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
with the line console.error(this.props.url, status, err.toString()
underlined.
Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.
EDIT:
I’ve checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.
EDIT 2:
It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727
instead of the expected http://localhost:3001/api/threads
.
I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What’s frustrating here is that this was working correctly the last time I worked on it and can’t find what I could have possibly changed to break it.
Author: Chukwuka Reuben
Introduction.
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?
- What does the «Unexpected token < in JSON at position 0» error mean?
- Different Reasons Why You Might Have This Error and Their Fixes.
- Hitting Any API endpoint that does not exist:
- Spelling Error
- Forgetting to stringify your object:
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:
localStorage.setItem('list', JSON.stringfy(list))
JSON.parse(localStorage.getItem('list'))
Enter fullscreen mode
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:
JSON.parse(undefined)
Enter fullscreen mode
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:
fetch('https://dummyjson.com/products/1')
.then(res => res.json())
.then(json => console.log(json))
Enter fullscreen mode
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:
fetch("https://dummyjson.com/myProduct/1")
.then((res) => res.json())
.then((json) => console.log(json));
Enter fullscreen mode
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.
localStorage.setItem("list",
list);
Enter fullscreen mode
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:
const getLocalStorage = () => {
let list = localStorage.getItem("list");
if (list) {
return (list = JSON.parse(localStorage.getItem("list")));
} else {
return [];
}
};
Enter fullscreen mode
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:
localStorage.setItem("list",
JSON.stringify(list))
Enter fullscreen mode
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.
A refresher on the purpose and syntax of JSON, as well as a detailed exploration of the JSON Parse SyntaxError in JavaScript.
Traveling deftly through to the next item in our JavaScript Error Handling series, today we’re taking a hard look at the JSON Parse
error. The JSON Parse
error, as the name implies, surfaces when using the JSON.parse()
method that fails to pass valid JSON as an argument.
In this article, we’ll dig deeper into where JSON Parse
errors sit in the JavaScript error hierarchy, as well as when it might appear and how to handle it when it does. Let’s get started!
The Technical Rundown
- All JavaScript error objects are descendants of the
Error
object, or an inherited object therein. - The
SyntaxError
object is inherited from theError
object. - The
JSON Parse
error is a specific type ofSyntaxError
object.
When Should You Use It?
While most developers are probably intimately familiar with JSON and the proper formatting syntax it requires, it doesn’t hurt to briefly review it ourselves, to better understand some common causes of the JSON Parse
error in JavaScript.
JavaScript Object Notation
, better known as JSON
, is a human-readable text format, commonly used to transfer data across the web. The basic structure of JSON consists of objects
, which are sets of string: value
pairs surrounded by curly braces:
{
"first": "Jane",
"last": "Doe"
}
An array
is a set of values
, surrounded by brackets:
[
"Jane",
"Doe"
]
A value
can be a string
, number
, object
, array
, boolean
, or null
.
That’s really all there is to the JSON syntax. Since values
can be other objects
or arrays
, JSON can be infinitely nested (theoretically).
In JavaScript, when passing JSON to the JSON.parse()
method, the method expects properly formatted JSON as the first argument. When it detects invalid JSON, it throws a JSON Parse
error.
For example, one of the most common typos or syntax errors in JSON is adding an extra comma separator at the end of an array
or object
value
set. Notice in the first few examples above, we only use a comma to literally separate values
from one another. Here we’ll try adding an extra, or «hanging», comma after our final value
:
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
var json = `
{
«first»: «Jane»,
«last»: «Doe»,
}
`
console.log(JSON.parse(json));
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}
Note: We’re using the backtick (`
) string syntax to initialize our JSON, which just allows us to present it in a more readable form. Functionally, this is identical to a string that is contained on a single line.
As expected, our extraneous comma at the end throws a JSON Parse
error:
[EXPLICIT] SyntaxError: Unexpected token } in JSON at position 107
In this case, it’s telling us the }
token is unexpected, because the comma at the end informs JSON that there should be a third value
to follow.
Another common syntax issue is neglecting to surround string
values within string: value
pairs with quotations ("
). Many other language syntaxes use similar key: value
pairings to indicate named arguments and the like, so developers may find it easy to forget that JSON requires the string to be explicitly indicated using quotation marks:
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
var json = `
{
«first»: «Jane»,
last: «Doe»,
}
`
console.log(JSON.parse(json));
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}
Here we forgot quotations around the "last"
key string
, so we get another JSON Parse
error:
[EXPLICIT] SyntaxError: Unexpected token l in JSON at position 76
A few examples are probably sufficient to see how the JSON Parse
error comes about, but as it so happens, there are dozens of possible versions of this error, depending on how JSON was improperly formatted. Here’s the full list:
JSON Parse Error Messages |
---|
SyntaxError: JSON.parse: unterminated string literal |
SyntaxError: JSON.parse: bad control character in string literal |
SyntaxError: JSON.parse: bad character in string literal |
SyntaxError: JSON.parse: bad Unicode escape |
SyntaxError: JSON.parse: bad escape character |
SyntaxError: JSON.parse: unterminated string |
SyntaxError: JSON.parse: no number after minus sign |
SyntaxError: JSON.parse: unexpected non-digit |
SyntaxError: JSON.parse: missing digits after decimal point |
SyntaxError: JSON.parse: unterminated fractional number |
SyntaxError: JSON.parse: missing digits after exponent indicator |
SyntaxError: JSON.parse: missing digits after exponent sign |
SyntaxError: JSON.parse: exponent part is missing a number |
SyntaxError: JSON.parse: unexpected end of data |
SyntaxError: JSON.parse: unexpected keyword |
SyntaxError: JSON.parse: unexpected character |
SyntaxError: JSON.parse: end of data while reading object contents |
SyntaxError: JSON.parse: expected property name or ‘}’ |
SyntaxError: JSON.parse: end of data when ‘,’ or ‘]’ was expected |
SyntaxError: JSON.parse: expected ‘,’ or ‘]’ after array element |
SyntaxError: JSON.parse: end of data when property name was expected |
SyntaxError: JSON.parse: expected double-quoted property name |
SyntaxError: JSON.parse: end of data after property name when ‘:’ was expected |
SyntaxError: JSON.parse: expected ‘:’ after property name in object |
SyntaxError: JSON.parse: end of data after property value in object |
SyntaxError: JSON.parse: expected ‘,’ or ‘}’ after property value in object |
SyntaxError: JSON.parse: expected ‘,’ or ‘}’ after property-value pair in object literal |
SyntaxError: JSON.parse: property names must be double-quoted strings |
SyntaxError: JSON.parse: expected property name or ‘}’ |
SyntaxError: JSON.parse: unexpected character |
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data |
To dive even deeper into understanding how your applications deal with JavaScript Errors, check out the revolutionary Airbrake JavaScript
error tracking tool for real-time alerts and instantaneous insight into what went wrong with your JavaScript code.
An Easier Way to Find JavaScript Errors
The first way to find a JSON Parse error is to go through your logs, but when you’re dealing with hundreds, if not thousands, of lines of code, it can be difficult to find that one line of broken code. With Airbrake Error and Performance Monitoring, you can skip the logs and go straight to the line of broken code resulting in the JSON Parse error.
Don’t have Airbrake? Create your free Airbrake dev account today!
Note: We published this post in February 2017 and recently updated it in April 2022.
The most common reason for this error is attempting JSON to parse an HTML or XML response. The HTML and XML documents start with <, and JSON identifies it as an unparsable string. It is also possible that you are requesting an api that you don’t have permission to access. In that case, you expect a JSON, but the server returns a permission denial HTML.
This article demonstrates several JSON parsing errors with code examples.
Reason for Unexpected token < in JSON error
Listed below is a simple express.js route that generates an HTML response. It can be any api endpoint. The api generates the HTML response <p>This is an HTML response</p>.
router.post("/user/create/html", (request, response) => {
const reply = "<p>This is an HTML response</p>"
response.set('Content-Type', 'text/html');
response.send(reply);
});
Now let’s find out what happens when we try to parse this response with the JSON parser. The code makes a post request to the endpoint that produces an HTML response. Then it tries to JSON parse the response.
const serverHtmlResponse = await axios.post('/user/create/html')
console.log(serverHtmlResponse.headers["content-type"])
console.log(serverHtmlResponse.data)
console.log(typeof serverHtmlResponse.data)
const htmlResponse = JSON.parse(serverHtmlResponse.data)
Note that the endpoint’s response type is text/html and the content is <p>This is an HTML response</p>. The content is not parsable. Thats the reason you see the first character of the content < in the error message.
Reason for Unexpected token o in JSON at position 1
That error happens when we attempt to JSON parse an object.
The below express.js route produces a JSON object as the response.
router.post("/user/create/json", (request, response) => {
const reply = "This is a JSON object response"
response.json({response:reply});
});
The response of this endpoint is {response: ‘This is a JSON object response’}. That is not a JSON string. It is an object. The console.log(typeof serverJsonResponse.data) proves the api response is an object.
const serverJsonResponse = await axios.post('/user/create/json')
console.log(serverJsonResponse.headers["content-type"])
console.log(typeof serverJsonResponse.data)
console.log(serverJsonResponse.data)
const jsonResponse = JSON.parse(serverJsonResponse.data)
Therefore, what happens here is JSON.parse(«[object Object]»)
and JSON complains about the character «o» it encountered first.
How to parse a JSON string correctly?
The JSON.parse() method accepts a string that correctly represents a JSON object. In other words, a string that is parsable into a JSON object.
Below is an express route that produces a JSON string like {«response»:»This is a JSON string response»}.
router.post("/user/create/jsonstring", (request, response) => {
const reply = `{"response":"This is a JSON string response"}`
response.json(reply)
});
The response is application/json, and the type is string. This type of response is parsable with JSON parser as long as the response string can represent a valid object.
const serverResponse = await axios.post('/user/create/jsonstring')
console.log(serverResponse.headers["content-type"])
console.log(typeof serverResponse.data)
console.log(serverResponse.data)
const jsonStringResponse = JSON.parse(serverResponse.data)
In this article you will learn what JSON is and how you can deal with errors occurring when parsing JSON data, such as «Unexpected Token < in JSON at Position 0.»
What Is JSON
JSON, which is an acronym for JavaScript Object Notation, is one of the most popular data formats used for transmitting data. It is a lightweight format and consists of name-value pairs. Values can be strings, arrays, or any other data that can be serialized.
In the old days XML was primarily used for interchanging data, but since JSON appeared it is often used as a replacement of XML. A JSON file should end with the .json
extension.
Below you can see an example of a JSON format.
{
"name": "animals",
"animals": [
"Dog",
"Cat",
"Mouse",
"Pig",
"Bear"
],
"hobbies": {
"football": false,
"reading": true
}
}
JSON format is quite similar to JavaScript objects, but it is not always the case. It is important to remember that every property name must be wrapped in double quotes.
// not valid JSON
{
x: 4
}
// valid JSON
{
"x": 4
}
Unexpected Token < in JSON at Position 0
From time to time when working with JSON data, you might stumble into errors regarding JSON formatting. For instance, if you try to parse a malformed JSON with the JSON.parse()
function or use the .json()
method on the fetch
object, it can result in a JavaScript exception being thrown. But don’t worry, it’s not the end of the world and we can handle it. There can be different causes for this happening so let’s see what we can do about it.
Is My JSON Formatted Correctly?
Projects sometimes require configuration that is sent to the client from a server. Just so you know, storing the config details as a JSON will be faster than using an object literal, as engines need to do more steps when running an object literal than JSON.parse()
, for instance. The performance comparison of JSON vs JavaScript is not a topic of this article so it will not be covered, but if you are interested, then you can read more about it here.
If you have a file with JSON data, one of the first things to do is to ensure that the data is formatted correctly. There are a few sites that can help you with that. These formatters not only will check if your JSON is formatted correctly, but they can also fix some of the errors, beautify it, or make it compact.
- https://jsonformatter.org/
- https://jsonformatter.curiousconcept.com/
- https://codebeautify.org/jsonvalidator
To be honest, one of the mistakes I am often guilty of myself is using single quotes instead of double quotes. The image below shows how a format checker can make your life easier.
If your JSON is formatted correctly, then it is time to check what else could be wrong.
My JSON is Formatted Correctly—What Next?
“Unexpected token < in JSON at position 0” is the error that I have seen most throughout my time of working as a software developer. Quite often it happens in a situation when fetch
function is used for sending an API request from a client. After receiving a response from a server, usually it is parsed to JSON.
fetch(‘url’).then(response => response.json())
The first thing to do in this situation is to confirm where the error is happening exactly. To ensure the error happens on the exact line we think it does, we can wrap the JSON parsing code in a try-catch block. Check the code below.
fetch("url").then(async response => {
try {
const data = await response.json()
console.log('response data?', data)
} catch(error) {
console.log('Error happened here!')
console.error(error)
}
})
If this is the culprit, then it will be clearly visible in the developer tools console, as “Error happened here!” will be displayed. Otherwise, you might need to look for it somewhere else. A good idea is to sometimes comment out code piece by piece to see when an error stops being thrown. You can also use an early return
statement.
The next step is to check if the data we are expecting to see is actually being sent from the server. As shown on the image below, head to the “Network” tab in DevTools, find the request, and click on the “Response” tab.
In this example, we can see a JSON string sent from the swapi
API, so it is correct. However, in a different case, the response could be in the XML format or the server could have sent an HTML file. The former could happen if you are dealing with a server that can return different responses depending on the content-type header provided. If this is the case, when you send a request, make sure you specify the content-type
header as shown below:
fetch(‘url’, {
method: ‘GET’,
headers: {
‘Content-Type’: ‘application/json’
}
}).then(response => response.json())
As for the latter, I have seen the server sending an HTML file on a few occasions. Usually, a reason for this was an incorrect URL provided to the fetch
method, or the API server route was not set up correctly. For example, if you have a Single Page Application and a backend running Express.js server, it could be set up to always serve an index.html
file. Therefore, always double-check your URLs and API routes configuration.
Conclusion
JSON is an extremely popular format and is commonly used for data interchanging. We have talked about what JSON is, and what we can do when a parsing error is thrown. For starters, always double-check if the values you are dealing with are what you expect them to be, and remember, console.log() is your friend.
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
You made an HTTP request, probably with Fetch, and it blew up with this error. Or a very similar one.
Ugh.
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:
fetch('/users').then(res => res.json())
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(theStringThatIsNotJson);
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:
fetch('/users')
// .then(res => res.json()) // comment this out for now
.then(res => res.text()) // convert to plain text
.then(text => console.log(text)) // then log it out
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.
// JSON.parse(someString) // comment this out temporarily
console.log(someString) // log out out, and see what's wrong
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.
Learning React can be a struggle — so many libraries and tools!
My advice? Ignore all of them
For a step-by-step approach, check out my Pure React workshop.
Learn to think in React
- 90+ screencast lessons
- Full transcripts and closed captions
- All the code from the lessons
- Developer interviews
Start learning Pure React now
Dave Ceddia’s Pure React is a work of enormous clarity and depth. Hats off. I’m a React trainer in London and would thoroughly recommend this to all front end devs wanting to upskill or consolidate.
Alan Lavender
@lavenderlens
The “unexpected token o in json at position 1” disturbs the program when you parse the already parsed object; you can have multiple options to solve. This article contains all the causes of this error, all solutions to those causes with coding examples, and experts’ advice. Keep on reading this article till the end to learn whatever is needed to know about this error.
Why Are You Getting an “Unexpected Token O in Json at Position 1” Error?
There are several reasons why you are getting this error. Let’s find out the causes.
– No Need To Use Json.parse
Some beginner developers make this mistake when using JSON.parse, having no need. You might already have a javascript object and don’t need to parse. This error often appears when trying to parse an object already in parsed form.
– API URL Endpoint
This error appears as the API URL endpoint serves the request with either an error or an included or used file.
– Javascript Object Data
You might get this error if you are using JSON.parse and your data is a javascript object. The first parameter of JSON.parse is expected to be a string, and if you have a javascript object, that will force the “[object object]” string.
– JSON or String Happens To Get Parsed
If JSON data or sting are parsed, you will get the error. If it is a string, it would be stringified.
– Getdata(Res)
If you are using getData(res), we see that “res” is already a parsed JSON object. Furthermore, using “res” with JSON.parse is useless. And can lead you to that error.
– JSON String in Quotes
You will face this error if you haven’t placed the full JSON strings in quotes.
Solution: You should place the full JSON strings in quotes, as shown in the example below:
Var cur_ques_details=’{“ques_id”:“49”,“Title”:“anything”}
If the object is already parsed into a JSON object, so you no longer need to pass it. But how can you accomplish the same thing without parsin? Well, you can do that by doing the following code:
<html>
<head>
</head>
<body>
<script type= “text/javascript”>
Var cur_ques_details = {“ques_id”:“67”:“ques_title”: “anything”};
document.writer(cur_ques_details.ques_title);
</script>
</body>
</html>
– When Nothing Helps
If you have tried all the solutions and are still unable to fix this issue, this is time to explore some of the issues that are usually not discussed much but create many problems.
Sometimes developers face the issue when running JSON.parse (message.data), getting a string back but not an object, and then rerunning JSON.parse to get the real object back. This is where no solutions mentioned above work. When they don’t have the set breakpoint, you won’t get this error while stepping through chrome. You might face the invalidity of JSON.
How To Fix It
We got to know the causes of this error. Let’s now find out the solutions.
– No Need To Use Json.parse
If you found that you are using JSON.parse unnecessarily, you just need to slightly change your code and remove the error. Sometimes using “userData” directly as an object helps a lot.
new Object().toString()
JSON.parse(new object())
JSON.parse(“[object object]”)
JSON.parse converts the input into a string. The toString() used in the above example is a method of javascript objects that returns [object object] by default, which results in the observed behavior.
You can also try the following:
var newData = userData.data.userList;
You should also avoid using JSON.parse without wrapping it in a try-catch block as shown in the below example.
Let userData = null;
Try{
userData=JSON.parse(payload);
} catch (e){
userData=payload;
}
– Use Json.stringify() Before Json.parse
Use the below line above the JSON.parse
var newData = JSON.stringify(userData)
Here the JSON.stringify will convert a javascript object to a string representation of it, which is the exact opposite of what JSON.parse does. You were getting the error because you were attempting to parse an object that was already an object. Using the above line before JSON.parse will convert it to a string to avoid the error.
– Use Jquery
You can also use jQuerry, as shown in the below example, which will help you debug.
Var yourval =JQuerry.parseJSON(JSON.stringify(data));
– API URL Endpoint
You can remove this error by hitting the endpoint using postman or looking at the network tab in the browser developer tool.
– Javascript Object Data
A simple solution could be if you use JSON.stringify before passing the data.
JSON.parse(JSON.stringify(userData))
– Json or String Happens To Get Parsed
If JSON data or string are to get parsed, the simple solution would be to remove the JSON producer. Let’s understand this by the following coding example.
@post
@produces({**MediaType.APPLICATION_JASON**})
public Response login(@QueryParam(“customerID”) String customerID, officer custm){
Return response.status(200).entity(“perfect”).build();
}
The response is expected to contain a “perfect” string return. The “@produces({**MediaType.APPLICATION_JASON**})” line attempted to parse the string to JSON, and that’s why you will get the same error. So removing that would work well.
Make sure you don’t make ajax requests and use JSON parse(“perfect”); otherwise, you will face token ‘o’.
– Getdata(Res)
If you have used “res” with “getData,” you know that it is already a JSON object, but if you want to use it again, you should do it in the following way;
Let data = res;
Rather than doing this:
Let data = JSON.parse(yes);
– When Nothing Helps
If you have tried all the solutions but still getting the error, there might be several things for you to understand. Let’s discover a few ones.
– No Need to Parse Again
One of the solutions could be not parsing the JSON a second time if you have already parsed it at once. Some developers parse the second time because they get an error when they parse the first time. Here you need to understand that not the type of string but the type of object.
You can access anything in the object, and when you parse the string to the JSON object for the first time, it is parsed, so you are not supposed to parse it again.
– The JSON String Is Not Well-formed
It is also possible that your JSON string data is not a well-formed JSON parsed string. Maybe the server sends you a multi-part message during and after the connection. So if this is the case, you should analyze if they are fully formed valid JSON strings.
– JSON Data in the Console
When you try to print a specific JSON data in the console and get the same error, that error is that the data is already parsed. So you would call the objects directly, but you can still get the “undefined” error message.
To solve this issue, you should iterate your data and try to print arguments of the function in the success, which might help you.
You can iterate through the result to print each title/URL. You can use for or for Each for that.
FAQs
– What Is JSON.parse?
The primary use of JSON is to exchange data to/from a web server. When data is being received from a web server, the information is always a string. Here the JSON.parse parses the data, and now the data has been converted from string to JavaScript object.
– Coding Example of Json.parse()
Let’s suppose we get the following text from a web server.
‘{“Name”:“Michaels”,“Age”:25, “City”: “London”}’
Now we will use the JSON.parse to convert the above string into the JavaScript object
const obj = JSON.parse(‘{“Name”:“Michaels”,“Age”:25, “City”: “London”}’);
The text should be in JSON format; otherwise, you will get an error.
– What Is Json.stringify()?
The JSON.stringify() method converts a JavaScript object to a JSON string.
– When is JSON.stringify() Used?
When we send the data, it goes to the server as a string. JSON.stringify() method converts JavaScripts data to a JSON-formatted string. When you need a ready-made JSON string to send, you can apply the JSON.stringify() method to JavaScript objects to produce a JSON string.
– What Is Jquery?
jQuery is a Javascript library used to simplify JavaScript programming. JQuery is one of the most used libraries of Javascript. jQuery takes many tasks that require the javascript code of many lines to accomplish, wraps the code into a method, and then you can just call that method and implement what you were doing by writing long codes before.
Conclusion:
Let’s conclude what we learned today:
- The leading cause of this error is parsing the already parsed object again, and you can’t parse the already parsed object.
- If you are attempting to parse JSON data or string, you should remove the JSON producer to eliminate the error.
- If you get an “undefined” error message, you should iterate your data and try to print arguments of the function in the success.
We learned why the “unexpected token o in json at position 1” error appears and how we can solve this error. This article explains the solutions to all the causes, so you don’t need to worry about this error anymore. Next time when you face this error, use this article as the guide.
- Author
- Recent Posts
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.