Safe JSON parsing strategies
Parse untrusted JSON safely with try/catch, small shape checks, defaults, and tiny helper utilities.
Why safe parsing?
Goal: Read JSON without surprises.
- try/catch around parse
- Small safeParse helper
- Shape checks for required fields
- Defaults for optional values

safeParse helper
Use a tiny safeParse to avoid crashes and to surface errors clearly.
// safeParse: never throws, returns { ok, value, error }
function safeParse(text) {
try {
const value = JSON.parse(text);
return { ok: true, value: value, error: null };
} catch (e) {
return { ok: false, value: null, error: String(e.message) };
}
}
// Demo
const good = safeParse("{\"name\":\"Ayla\",\"age\":20}");
const bad = safeParse("{broken}");
console.log("good.ok:", good.ok, "name:", good.value && good.value.name);
console.log("bad.ok:", bad.ok, "error:", bad.error);

All lessons in this course
- JSON.parse / JSON.stringify basics
- Structured cloning & URLSearchParams
- Safe JSON parsing strategies