0Pricing
JavaScript Academy · Lesson

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
Safe JSON parsing strategies — illustration 1

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);
Safe JSON parsing strategies — illustration 2

All lessons in this course

  1. JSON.parse / JSON.stringify basics
  2. Structured cloning & URLSearchParams
  3. Safe JSON parsing strategies
← Back to JavaScript Academy