Bad JSON is common: a server returns an HTML error page, stored data is corrupted, a user pastes the wrong thing. Your code should survive it.
The error you will see
try {
JSON.parse("{name: 'Maya'}");
} catch (error) {
console.log(error.name); // → SyntaxError
console.log(error.message.length > 0); // → true
}
The message depends on the browser, but it usually tells you the position of the problem, for example Unexpected token n in JSON at position 1 or Expected property name or ‘}’.
The classic: “Unexpected token <“
Unexpected token '<' means your “JSON” actually starts with <. That is HTML. The server probably sent an error page (404, 500, a login page) instead of JSON. Check the URL, the status code and the Network panel before blaming your parsing code. See Fetch Response Handling.
Another: “undefined” is not valid JSON
try {
JSON.parse(undefined);
} catch (error) {
console.log(error.name); // → SyntaxError
}
This happens when reading a missing value, for example localStorage.getItem("missing") returns null (which parses to null, fine), but passing undefined throws.
A safe parse helper
function parseJSON(text, fallback) {
if (typeof text !== "string") return fallback;
try {
return JSON.parse(text);
} catch (error) {
console.warn("Invalid JSON:", error.message);
return fallback;
}
}
console.log(parseJSON('{"theme":"dark"}', {})); // → { theme: dark }
console.log(parseJSON("oops", { theme: "light" })); // → { theme: light }
Valid JSON is not the same as the data you expect
Parsing can succeed and still give you the wrong shape. Check what you need before using it.
function parseJSON(text, fallback) {
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
function readUser(text) {
const data = parseJSON(text, null);
if (data === null || typeof data !== "object") return null;
if (typeof data.name !== "string") return null;
return { name: data.name, age: Number(data.age) || 0 };
}
console.log(readUser('{"name":"Maya","age":"28"}')); // → { name: Maya, age: 28 }
console.log(readUser('{"age":28}')); // → null
console.log(readUser("[]")); // → null
For large or important data, a schema validation library can check shapes systematically.
Debugging bad JSON
- Print the raw text with
console.log(text)before parsing. - Paste it into a JSON validator.
- Check for the common issues: single quotes, trailing commas, unquoted keys, comments, HTML instead of JSON.
Related
try...catch statement is explained in the Error Handling chapter.