How to Fix JSON Parse Error Unexpected Token: A Definitive Guide

A “JSON parse error: unexpected token” means JSON.parse() (or response.json()) received a string that is not valid JSON. The token shown in the error is simply the first character that broke parsing, which is why the same message can point to very different root causes.
This guide walks through the most common tokens developers hit in browsers and Node.js, how to confirm what you are actually parsing, and the fixes that prevent the error from coming back.
You will see these patterns repeatedly:
- Unexpected token < when an API returns an HTML error page.
- Unexpected token o when a JavaScript object is accidentally passed into JSON.parse().
- Quote and comma issues (single quotes and trailing commas).
- Hidden characters like a BOM at the start of a file.
What Does an Unexpected Token Error Actually Mean?
At a basic level, the JavaScript engine is telling you the input does not follow JSON rules.
JSON.parse() expects a valid JSON string. The moment it encounters a character that cannot appear in that position, it stops and throws a syntax error.
A quick analogy
If a recipe calls for two eggs and you hand over a rock, the cook cannot continue. In the same way, a JSON parser stops the moment it encounters a character that cannot appear at that position.
The Most Common Culprit: Unexpected Token < at Position 0
If you see this exact error, it almost always means an HTML page is being parsed as JSON. This typically happens when fetch() (or an Ajax call) receives an error response and the code still calls response.json().
The Scenario
Imagine you are fetching user data from /api/users. Your code looks like this:
fetch('/api/users')
.then(response => response.json())
.then(data => console.log(data));
If the path is wrong or the server is down, the response might be an HTML error page that starts with .
The Fix
That HTML page begins with <, but valid JSON must start with { or [. The safest pattern is to check the response status before calling response.json():
async function safeFetch() {
const response = await fetch('/api/users');
if (!response.ok) {
console.error("The server sent an error page instead of JSON data.");
return;
}
const data = await response.json();
console.log(data);
}
Checking response.ok prevents your code from attempting to parse non JSON content.
The Second Most Common Issue: Single Quotes vs. Double Quotes
This mistake shows up often when JSON is typed by hand or copied from a JavaScript object.
The Scenario
In JavaScript, single quotes and double quotes often behave the same. You can write 'name' or "name" and it works. JSON is stricter: keys and string values must use double quotes.
If you try to parse this:
const badJson = "{ 'name': 'Imad' }";
JSON.parse(badJson); // Error!
You will get an unexpected token error pointing at the first single quote.
The Fix
If you need a JSON string, prefer JSON.stringify() instead of concatenating strings manually.
const validObject = { name: "Imad" };
const safeString = JSON.stringify(validObject);
console.log(JSON.parse(safeString)); // Works perfectly!
For large files with inconsistent quoting, a formatter or cleanup tool is usually faster than fixing quotes one by one.
Dealing with Trailing Commas
Modern JavaScript has become very forgiving. You can put a comma after the last item in an array or an object, and it will not cause any issues. JSON, however, has not gotten the memo.
The Scenario
Consider this configuration file:
{
"theme": "dark",
"version": "1.0.2",
}
That tiny comma after the version number is a fatal error in the eyes of JSON.parse(). The parser sees the comma and expects another key. When it finds a closing brace instead, it throws an unexpected token error.
The Fix
You must remove trailing commas. If you are dealing with thousands of lines, a JSON formatter or a linter like ESLint is the fastest way to catch these issues early. A single extra comma is very easy to miss in a large file.
The Mystery of Unexpected Token o at Position 1
This is perhaps the most confusing error for beginners because it usually means you are trying to parse something that is already a JavaScript object.
The Scenario
When you see this error, it usually means an actual object was passed into JSON.parse(). When an object is coerced into a string, it becomes [object Object]. The second character in that string is the letter o.
const myData = { id: 1 };
JSON.parse(myData); // Error: Unexpected token o in JSON at position 1
The Fix
Check your variables. If the data is already an object, it does not need parsing. JSON.parse() is only for raw strings (for example, an API response body or a line read from a file). A quick typeof check can prevent this mistake:
if (typeof data === "string") {
data = JSON.parse(data);
}
Invisible Killers: The BOM and Hidden Characters
Sometimes the JSON looks perfect, but parsing still fails. A common cause is a Byte Order Mark (BOM) or other invisible whitespace characters at the start of the string.
The BOM Problem
Some text editors (especially on Windows) add an invisible marker at the very beginning of a file to specify the encoding. This is known as a BOM. While it is useful for some applications, JavaScript does not know what to do with it.
The Fix
If you suspect a hidden character is causing issues, you can "sanitize" your string before parsing it by using a regular expression to remove non breaking spaces and other invisible markers:
const sanitizedData = rawData.trim().replace(/^\uFEFF/, "");
const cleanJson = JSON.parse(sanitizedData);
Including a .trim() call when reading from a file helps because files often end with an extra empty line or whitespace that can trip up strict parsers.
Environment Specific Insights
Browser Debugging
When debugging in the browser, use the Network tab in your developer tools. Click the failed request and inspect the Response panel. If you see HTML instead of JSON, the error is happening before parsing even starts.
Also watch for CORS issues. A blocked or redirected request can lead to an unexpected response body, which then bubbles up as a parse error.
Node.js Debugging
On the server side, you often deal with Buffer values when reading files. If you forget to specify an encoding, you might pass raw binary data into the parser.
// This will likely fail!
const data = fs.readFileSync('data.json');
JSON.parse(data);
// This will succeed!
const data = fs.readFileSync('data.json', 'utf8');
JSON.parse(data);
Always ensure you are working with a string before calling the parse function.
How to Handle Exceptionally Large JSON Files
If you are working with a file that is several hundred megabytes or even gigabytes in size, a single JSON.parse() call can be risky. It can consume enough memory to crash the process with an out of memory error.
In that situation, use a streaming approach. Streaming parses the file piece by piece instead of loading everything into RAM at once. In Node.js, libraries like stream json can help, and splitting the file into smaller chunks can also make debugging and processing far more predictable.
Comparison Table: Common Unexpected Tokens and Their Meanings
| Unexpected Token | What it Usually Means | How to Fix It |
|---|---|---|
| < | You are parsing an HTML error page. | Check the API URL and response status. |
| o | You are parsing a JavaScript object. | Stop parsing. The data is already an object. |
| u | You are parsing the word "undefined". | Verify your API is actually returning data. |
| ' | You used single quotes instead of double quotes. | Standardize your JSON to use double quotes. |
| [ | You expected an object but got an array. | Access the data via index 0 first. |
| </span> | There is an unescaped backslash in the string. | Escape backslashes correctly in the source string. |
Pro Tips for Error Prevention
Most unexpected token errors are easier to prevent than to debug. These habits catch the issue earlier and make failures obvious when they happen:
- Use schema validation. Libraries like Zod or Joi let you define the shape of your data so bad responses fail fast and clearly.
- Log the raw string before parsing. In a catch block, log the exact value being parsed so it is obvious whether it is HTML, empty, or already an object.
- Automate formatting and generation. Prefer JSON.stringify() and formatter tools over hand written JSON, especially for larger files.
Related Tools and Guides
If you are currently wrestling with data format issues, these resources are the most directly useful:
- How to Format JSON in Notepad++ for quickly cleaning up messy files.
- JSON Flattener for simplifying nested structures before parsing.
- JSON File Splitter for working with large files in smaller, safer chunks.
Final Thoughts
A JSON parse error with an unexpected token is almost never random. It is a clear signal that the input is not valid JSON, even if it looks close at a glance. Once you treat it as an input verification problem, the fix becomes straightforward.
When this error hits in production, the fastest workflow is simple: inspect the raw response, confirm whether you have a string, then validate formatting and hidden characters before reaching for bigger changes. Most teams eliminate repeat incidents by logging the raw value on failures and standardizing on JSON.stringify() and formatter driven workflows.
Read More
All Articles
8 Best Online Tools for Validating JSON Syntax in 2026
Got mangled JSON from an API? These 8 online validators will tell you exactly where it's broken. No signup, no downloads. Paste your JSON and get useful error messages instead of cryptic line numbers.

How JSON Powers Everything: The Hidden Force Behind Modern Web Applications
Learn how JSON powers modern web applications, APIs, and online tools. Discover why JSON became the universal data format and how it enables everything from file converters to real-time applications.

How to Add an Image in JSON: A Comprehensive Guide
Learn how to add an image to a JSON object using URLs, file paths, or base64 encoding. This guide provides examples and best practices for each method.