Sub topic 5
Handling Invalid JSON Without Crashing
JSON.parse accepts only strict JSON. If the text breaks the grammar anywhere, it throws a SyntaxError and returns nothing. In real programs the text usually comes from places you don't control: API responses, files, localStorage, message queues, and user input. One bad byte in that text can crash a request handler or blank a page. This chapter covers why parsing fails, how to catch failures without hiding real bugs, and how to give callers a result they can't misread.
This chapter assumes you know try/catch, the difference between JSON syntax and JavaScript object literals, and how basic JSON.parse calls work. Revivers and security hardening come in later chapters.
What JSON.parse Does When the Input Is Bad
JSON.parse doesn't do partial work. It reads the whole string, and if any part is invalid, it throws before returning. You never get a half-built object back.
try {
JSON.parse('{"name": "Ada", "age": }');
} catch (err) {
console.log(err instanceof SyntaxError); // true
console.log(err.name); // "SyntaxError"
console.log(typeof err.message); // "string"
}The error is always a SyntaxError, but the message text depends on the engine. V8 (Chrome, Node.js) prints something like Unexpected token '}', ..."age": }" is not valid JSON. Firefox says JSON.parse: unexpected character at line 1 column 24 of the JSON data. Safari's wording is different again.
Common Causes of Invalid JSON
Most parse failures come from a short list of mistakes. Many of them are valid JavaScript but invalid JSON, which is why people often get caught by them.
| Input | Why it fails |
|---|---|
| `{'a': 1}` | Strings and keys must use double quotes |
| `{a: 1}` | Keys must be quoted strings |
| `{"a": 1,}` | Trailing commas are not allowed |
| `{"a": 1 // note}` | Comments are not allowed |
| `{"a": NaN}` | `NaN` and `Infinity` are not JSON values |
| `{"a": undefined}` | `undefined` is not a JSON value |
| `""` (empty string) | There is no value to parse |
| `<!DOCTYPE html>...` | An HTML error page arrived instead of JSON |
| `"\uFEFF{}"` | A byte-order mark is not JSON whitespace |
| `{"a": "line1` + newline + `line2"}` | Raw control characters must be escaped inside strings |
Some inputs look as if they should fail and don't. Leading and trailing whitespace is fine: JSON.parse(" 42\n") returns 42. A bare primitive is valid JSON, so JSON.parse("true"), JSON.parse('"hi"'), and JSON.parse("null") all succeed.
Non-string inputs are coerced first
JSON.parse converts its argument to a string before parsing. That leads to some surprising results:
console.log(JSON.parse(null)); // null (String(null) is "null", valid JSON)
console.log(JSON.parse(123)); // 123 ("123" is valid JSON)
console.log(JSON.parse(true)); // true
try {
JSON.parse(undefined); // String(undefined) is "undefined"
} catch (err) {
console.log(err instanceof SyntaxError); // true
}
try {
JSON.parse({}); // String({}) is "[object Object]"
} catch (err) {
console.log(err instanceof SyntaxError); // true
}The null case matters in practice. localStorage.getItem returns null when a key is missing. JSON.parse(localStorage.getItem("settings")) therefore returns null without throwing, and code that then reads settings.theme crashes with a TypeError somewhere else. The {} case is the other classic bug: code that calls JSON.parse on something that is already an object.
The Basic Safe-Parse Pattern
The simplest guard wraps the call and returns a fallback when parsing fails:
function safeParse(text, fallback = null) {
try {
return JSON.parse(text);
} catch (err) {
if (err instanceof SyntaxError) return fallback;
throw err;
}
}
console.log(safeParse('{"a":1}')); // { a: 1 }
console.log(safeParse("{'a':1}")); // null
console.log(safeParse('{"a":1,}', {})); // {}The instanceof check is there on purpose. A bare catch that returns the fallback for every error would also swallow errors that aren't about bad input. Examples are a bug inside a reviver function you pass later, or a RangeError from a very deeply nested document. Those are real problems, and silently turning them into null makes them much harder to find. Catch the error you expect and rethrow the others.
The ambiguity problem
safeParse has a weakness. If it returns null, the caller can't tell whether the input was invalid or whether it was the valid JSON text "null". The same applies to any fallback value that might also appear in real data. When the difference matters, return a result object instead:
function tryParse(text) {
if (typeof text !== "string") {
return { ok: false, error: new TypeError(`Expected a string, got ${typeof text}`) };
}
try {
return { ok: true, value: JSON.parse(text) };
} catch (err) {
if (err instanceof SyntaxError) return { ok: false, error: err };
throw err;
}
}
const inputs = ['{"a":1}', "null", "{oops}", undefined];
for (const input of inputs) {
const result = tryParse(input);
if (result.ok) {
console.log("parsed:", result.value);
} else {
console.log("failed:", result.error.name);
}
}
// parsed: { a: 1 }
// parsed: null
// failed: SyntaxError
// failed: TypeErrorThis version also rejects non-string input up front, so the coercion surprises from the previous section can't slip through. The caller has to check ok before reading value, which makes the failure case obvious in the code.
Valid JSON Is Not the Same as Correct Data
A successful parse only tells you the text is grammatically valid. It says nothing about whether the result has the shape your code expects. JSON.parse("[]") and JSON.parse('"hello"') both succeed, and code expecting { name, age } will still break on them. Check the shape after parsing:
function parseUser(text) {
let data;
try {
data = JSON.parse(text);
} catch (err) {
if (err instanceof SyntaxError) {
return { ok: false, error: "Body is not valid JSON" };
}
throw err;
}
const isObject = typeof data === "object" && data !== null && !Array.isArray(data);
if (!isObject) return { ok: false, error: "Expected a JSON object" };
if (typeof data.name !== "string") return { ok: false, error: "name must be a string" };
if (!Number.isInteger(data.age)) return { ok: false, error: "age must be an integer" };
return { ok: true, value: { name: data.name, age: data.age } };
}
console.log(parseUser('{"name":"Ada","age":36}')); // { ok: true, value: { name: 'Ada', age: 36 } }
console.log(parseUser("[1,2,3]")); // { ok: false, error: 'Expected a JSON object' }
console.log(parseUser('{"name":"Ada","age":"36"}'));// { ok: false, error: 'age must be an integer' }
console.log(parseUser("{name:'Ada'}")); // { ok: false, error: 'Body is not valid JSON' }Building a fresh object from the checked fields means unexpected extra properties don't reach the rest of the program. For larger payloads, a schema library such as Zod, Ajv, or Valibot does the same job declaratively. The idea stays the same: parse first, then validate, and only then trust the data.
Parsing HTTP Responses
response.json() in the Fetch API is JSON.parse applied to the body, and it rejects with a SyntaxError on bad input. The most common real-world parse error is Unexpected token '<'. It usually means a server, proxy, or CDN sent back an HTML error page. Checking the status and content type first gives you a much clearer error:
async function getJson(url) {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP ${res.status} from ${url}`);
}
const type = res.headers.get("content-type") ?? "";
if (!type.includes("application/json")) {
throw new Error(`Expected JSON from ${url}, got "${type}"`);
}
const text = await res.text();
try {
return JSON.parse(text);
} catch (err) {
if (err instanceof SyntaxError) {
const preview = text.slice(0, 80);
throw new Error(`Invalid JSON from ${url}: ${preview}`, { cause: err });
}
throw err;
}
}
getJson("https://jsonplaceholder.typicode.com/todos/1")
.then((todo) => console.log(todo.title))
.catch((err) => console.error(err.message));Reading the body with res.text() before parsing lets you put a short preview of the bad text into the error. That preview is often enough to diagnose the problem. Passing { cause: err } keeps the original SyntaxError attached for debugging. Keep the preview short, and don't log it if the body might contain tokens or personal data.
Recovering Stored Data
Data in localStorage, files, or caches can be corrupted, truncated, or written by an older version of your app. A good loader treats every failure as "use defaults" and repairs the stored value:
const DEFAULT_SETTINGS = { theme: "light", fontSize: 14 };
function loadSettings(storage) {
const raw = storage.getItem("settings");
if (raw === null) return { ...DEFAULT_SETTINGS };
try {
const parsed = JSON.parse(raw);
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
throw new SyntaxError("settings is not an object");
}
return { ...DEFAULT_SETTINGS, ...parsed };
} catch (err) {
if (!(err instanceof SyntaxError)) throw err;
console.warn("Resetting corrupt settings:", err.message);
storage.setItem("settings", JSON.stringify(DEFAULT_SETTINGS));
return { ...DEFAULT_SETTINGS };
}
}
// A tiny in-memory stand-in for localStorage so this runs in Node.js too
const memory = new Map([["settings", '{"theme":"dark",']]);
const storage = {
getItem: (k) => (memory.has(k) ? memory.get(k) : null),
setItem: (k, v) => memory.set(k, String(v)),
};
console.log(loadSettings(storage)); // { theme: 'light', fontSize: 14 } after a warning
console.log(memory.get("settings")); // {"theme":"light","fontSize":14}Spreading parsed values over the defaults also fills in fields that older stored versions didn't have.
Common Mistakes Summary
| Mistake | Consequence | Fix |
|---|---|---|
| No `try/catch` around `JSON.parse` | One bad input crashes the handler | Wrap the call or use a helper |
| Bare `catch` that returns a fallback | Hides real bugs | Check `instanceof SyntaxError` and rethrow others |
| Using `null` as both fallback and data | Callers can't tell failure from valid `null` | Return `{ ok, value, error }` |
| Parsing `getItem` output without a null check | `null` result crashes later code | Check for `null` before parsing |
| Trusting a successful parse | Wrong-shaped data crashes later code | Validate the shape after parsing |
| Matching on `err.message` | Breaks across engines | Match on the error type only |
Exercise
A teammate writes const config = JSON.parse(localStorage.getItem("config")) || {}; and says it can never throw. Name one input for which it throws, and one for which it silently returns a non-object that breaks later code.
Show answer
It throws a SyntaxError if the stored value is malformed, for example the truncated text '{"a":1'. It silently returns a non-object if the stored value is valid JSON for a truthy primitive or an array, for example '"dark"' gives the string "dark" and '[1]' gives an array. The || {} only covers falsy results such as a missing key (null), 0, or "".
Exercise
Why does the tryParse helper rethrow errors that are not SyntaxError instead of returning { ok: false }?
Show answer
Errors other than SyntaxError don't mean the input was bad. They point to a real problem, such as a bug in a reviver or a stack overflow from deeply nested input. Turning them into an ordinary "invalid input" result would hide the bug and make it look like user error. Rethrowing lets them reach normal error reporting.
Exercise
A fetch call fails with "Unexpected token '<'". What most likely happened, and which two checks before parsing would give a clearer error?
Show answer
The server returned HTML, usually an error or login page, instead of JSON. Checking res.ok (the HTTP status) and checking that the Content-Type header includes "application/json" would both catch this before JSON.parse runs.