JSON & try/catch
Recover from bad data
Lesson 10 of 20 · 9 min · Module 4: Reliable features
Data from a file or service often arrives as JSON text. Valid text can become a useful value; malformed text should not stop your whole program.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Distinguish JSON text from JavaScript objects
- Catch an expected parsing failure
- Preserve valid values of different types
The idea
JSON.parse(text) converts JSON into JavaScript values and throws for malformed input. A try/catch block provides a recovery path.
try {
const settings = JSON.parse('{"theme":"dark"}');
console.log(settings.theme);
} catch (error) {
console.log("Could not read settings.");
}
01JSON is a data format
JSON object keys and string values use double quotes. JavaScript object literal syntax is more permissive, so an object literal is not automatically valid JSON text.
02Choose a clear fallback
The null fallback signals that parsing did not produce a usable result here. Valid JSON null also parses to null; a production API needing to distinguish those cases could return a separate success flag.
Your turn
safeParse(text) to return the parsed JSON value when valid and null when parsing fails. Valid arrays and numbers must also work.What the checks look for
- Parses objects
- Parses arrays and numbers
- Recovers from malformed text
Take this with you
Handle failures where they are expected, and keep the success path simple.