Sub topic 2
Handling Invalid JSON Without Crashing
This chapter assumes you know try/catch, arrow functions, and the basics of JSON.parse and JSON.stringify. It covers three practical skills: surviving bad input, shaping output with a replacer, and making output readable.
Catching Parse Errors
JSON.parse throws a SyntaxError when its input is not valid JSON. Input from a network, a file, or localStorage can be truncated or hand-edited. If you leave the error uncaught, it crashes the calling code.
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)The instanceof check matters. Only parse failures get the fallback, and any other error is rethrown so it stays visible.
Filtering and Transforming with a Replacer
The second argument to JSON.stringify is a replacer. A replacer function receives each (key, value) pair and returns the value to write. If it returns undefined, the property is left out. A replacer array instead lists the property names to keep.
const account = { id: 7, user: "ada", password: "secret" };
const redacted = JSON.stringify(
account,
(key, value) => (key === "password" ? undefined : value)
);
console.log(redacted); // {"id":7,"user":"ada"}
console.log(JSON.stringify(account, ["id", "user"]));
// {"id":7,"user":"ada"}The function is called first with the key "" and the whole object as the value. Always return value for keys you don't handle, or you will drop the entire output.
Pretty-Printing with space
The third argument indents the output. A number sets that many spaces per level, capped at 10. A string such as "\t" is used as the indent itself, and only its first 10 characters count. Pass null as the replacer if you only want formatting.
const config = { port: 8080, hosts: ["a", "b"] };
console.log(JSON.stringify(config, null, 2));
// {
// "port": 8080,
// "hosts": [
// "a",
// "b"
// ]
// }Use indentation for logs and config files people read. Leave it out for network payloads, where the extra whitespace only adds bytes.
Exercise
Write one JSON.stringify call that leaves out any property named "token", indents with 4 spaces, and keeps every other property.
Show answer
JSON.stringify(obj, (key, value) => (key === "token" ? undefined : value), 4). The replacer returns undefined only for "token", returns value for everything else (including the root key ""), and 4 sets the indent.
Exercise
Why should safeParse rethrow errors that are not SyntaxError?
Show answer
Only a SyntaxError means the input was malformed. Swallowing other errors would hide real bugs behind a silent fallback value.