Sub topic 5
Handling Invalid JSON Without Crashing
This chapter assumes you know how JSON.parse turns text into values and that you're comfortable with try/catch. The topic here is what happens when the text isn't valid JSON, and how to handle that failure on purpose so it doesn't take down your program.
Why parsing fails
JSON.parse is strict. If the input breaks any rule of the JSON grammar, it throws a SyntaxError and returns nothing. Common causes in real code:
- An HTML error page arrives where you expected an API response, for example
<!DOCTYPE html>.... - The text was hand-written using JavaScript habits, such as single quotes, unquoted keys, trailing commas, or comments.
- The input is an empty string, which often comes from an empty response body or a missing
localStoragekey. - A network drop or a size limit cut the text off partway through.
The exact error message differs between engines. V8, SpiderMonkey, and JavaScriptCore each word it differently, so don't write logic that depends on the message text. Check the error type instead.
A safe parsing helper
The usual pattern wraps JSON.parse in a function that catches only SyntaxError and returns a fallback value:
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 (single quotes are not valid JSON)
console.log(safeParse('{"a":1,}')); // null (trailing commas are not valid JSON)
console.log(safeParse("")); // null (empty string is not valid JSON)The throw err line matters. A bare catch that returns the fallback for every error would also hide bugs, such as a reviver function that throws a TypeError. Re-throwing anything that isn't a parse failure keeps those bugs visible.
When a fallback value is ambiguous
Returning null on failure has a weakness. The text "null" is valid JSON and also parses to null, so the caller can't tell success from failure. If that difference matters to you, return a result object instead:
function tryParse(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch (err) {
if (err instanceof SyntaxError) return { ok: false, error: err };
throw err;
}
}
const r1 = tryParse("null");
const r2 = tryParse("not json");
console.log(r1); // { ok: true, value: null }
console.log(r2.ok, r2.error instanceof SyntaxError); // false trueNon-string input is coerced
JSON.parse converts its argument to a string before parsing it. That causes some surprising results:
| Call | Result |
|---|---|
| `JSON.parse(null)` | `null` (because `"null"` is valid JSON) |
| `JSON.parse(undefined)` | throws `SyntaxError` |
| `JSON.parse(42)` | `42` |
| `JSON.parse({})` | throws `SyntaxError` (`"[object Object]"`) |
Parsing response bodies
response.json() in the Fetch API runs the same parser and rejects its promise with a SyntaxError when the body is invalid. Use try/catch with await:
async function readJson(response) {
try {
return await response.json();
} catch (err) {
if (err instanceof SyntaxError) {
console.error("Body was not valid JSON");
return null;
}
throw err;
}
}
readJson(new Response('{"ok":true}')).then(console.log); // { ok: true }
readJson(new Response("<html>Error</html>")).then(console.log); // logs error, then nullExercise
A colleague writes try { return JSON.parse(text, reviver); } catch { return {}; }. What two problems does this have?
Show answer
First, it catches every error, so a bug that makes the reviver throw (for example a TypeError) is silently turned into {} and hidden. Second, {} is a fallback you can't tell apart from valid input "{}", so callers can't detect a failure. The fix is to re-throw anything that isn't a SyntaxError and to return a result object such as { ok, value, error }.
Exercise
What does safeParse(null, "fallback") return, and why?
Show answer
It returns null, not "fallback". JSON.parse converts null to the string "null", which is valid JSON, so no error is thrown and the fallback is never used.