When a JSON parse error shows up, most developers immediately start checking whether the JSON is formatted correctly. But a lot of the time, the problem isn't the JSON itself — it's that what you passed in wasn't JSON at all.
This article breaks down the errors by message. For each one: what it's actually telling you, where the real problem is, and how to fix it.
Unexpected token '<', "<!DOCTYPE "... is not valid JSON
This is the most common one. Almost every frontend developer has seen it.
It doesn't mean "your JSON is malformed." It means "you didn't receive JSON at all — you received an HTML page."
Why would you receive HTML? Common causes:
- The API URL is wrong, hitting a route that doesn't exist, so the server returned a 404 page
- You're not authenticated, and the server redirected you to a login page
- The server threw an error and returned a 500 error page
- In local development, the proxy isn't configured correctly and the request is hitting the frontend dev server, which returns index.html
// Problematic code
fetch('/api/user')
.then(res => res.json()) // if res is HTML, this throws immediately
.then(data => console.log(data));
// Better approach: check the response first
fetch('/api/user')
.then(res => {
if (!res.ok) {
throw new Error(`HTTP error: ${res.status}`);
}
const contentType = res.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error(`Expected JSON, got: ${contentType}`);
}
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));
When you see this error, don't look at the JSON first — look at the network request. Open DevTools → Network → find the request → check what's actually in the Response tab. It's almost always an HTML page with an error message in it, and that's where the real clue is.
Unexpected token 'u', "undefined" is not valid JSON
You called JSON.parse(undefined).
undefined is not a string, not JSON, and passing it in will always throw. This typically happens in one of these situations:
// Case 1: variable was never assigned
let data;
JSON.parse(data); // data is undefined
// Case 2: pulled the wrong field from an object
const response = { result: '{"name":"Alice"}' };
JSON.parse(response.data); // response.data is undefined, not result
// Case 3: the key was never stored in localStorage
const saved = localStorage.getItem('user'); // returns null if missing
// In some cases this leads to undefined being passed downstream
Fix: check the value before parsing.
const raw = localStorage.getItem('user');
if (raw) {
const user = JSON.parse(raw);
}
// More defensive
function safeParse(str) {
if (!str || typeof str !== 'string') return null;
try {
return JSON.parse(str);
} catch {
return null;
}
}
SyntaxError: Unexpected end of JSON input
The JSON started fine but got cut off before it was complete.
JSON.parse('{"name":"Alice"'); // missing closing }
JSON.parse(''); // empty string
JSON.parse('[1, 2, 3'); // array never closed
In real projects, the most common cause is a network request that got interrupted — only part of the response body arrived before the connection dropped. Another cause is a backend that's building JSON strings manually (which it shouldn't) with a bug that leaves the string incomplete.
To debug, read the raw string first:
fetch('/api/data')
.then(res => res.text()) // use text() instead of json()
.then(text => {
console.log('raw response:', text);
console.log('last 20 chars:', text.slice(-20));
return JSON.parse(text);
});
TypeError: Converting circular structure to JSON
This one happens during JSON.stringify(), not JSON.parse().
A circular reference means an object directly or indirectly references itself:
const obj = { name: 'Alice' };
obj.self = obj; // obj now references itself
JSON.stringify(obj); // TypeError: Converting circular structure to JSON
The most common place this shows up in real projects is trying to stringify Express's req or res objects directly:
// Wrong: req has circular references internally
app.post('/log', (req, res) => {
console.log(JSON.stringify(req)); // throws
});
// Right: only pull out what you need
console.log(JSON.stringify({
method: req.method,
url: req.url,
body: req.body,
headers: req.headers
}));
If you genuinely need to serialize an object that might have circular references, use a custom replacer:
function safeStringify(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return '[Circular]';
seen.add(value);
}
return value;
});
}
undefined, Functions, and Date Objects Silently Disappear or Change Shape
JSON doesn't support all JavaScript types. Some values get silently transformed during JSON.stringify() — no error, but the result isn't what you expect:
const obj = {
name: 'Alice',
fn: function() {}, // function
undef: undefined, // undefined
date: new Date(), // Date object
nan: NaN, // NaN
inf: Infinity // Infinity
};
console.log(JSON.stringify(obj));
// {"name":"Alice","date":"2026-04-11T02:13:20.000Z","nan":null,"inf":null}
// fn and undef just disappeared
// date became an ISO string
// NaN and Infinity became null
If your object contains these types, handle them before serializing:
// Date: convert to ISO string explicitly
const data = {
created_at: new Date().toISOString()
};
// undefined values: use null instead
const data = {
middleName: null // not undefined
};
Debugging Checklist
When a JSON error shows up, work through it in this order.
Step 1: Read the raw content, not just the error message. Change response.json() to response.text() and print what you actually received. Confirm what you're working with before anything else.
Step 2: Find the position in the error. Most JSON errors include a position or line number. Go to that character and look at what's around it.
Step 3: Match the error type to its cause. Starts with < — it's HTML. Says undefined — variable wasn't initialized. Says end of input — the string was cut off. Says circular structure — object references itself.
For syntax issues like single quotes, trailing commas, and unquoted keys, paste the broken JSON into the JSON Formatter tool — the smart repair feature pinpoints and fixes the most common issues automatically.
Article URL:https://toolshu.com/en/article/json-parse-error-fix
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License 。



Loading...