How do you safely parse a JSON string into an object with try-catch in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you safely parse a JSON string into an object with try-catch in JavaScript?

message-square
0

To safely parse a JSON string into an object in JavaScript, wrap JSON.parse(jsonString) inside a try...catch block so malformed JSON—which throws a SyntaxError—does not crash your application, and return a fallback value (such as null or a default object) when parsing fails. After parsing succeeds, verify the parsed result matches the shape you expect (for example, checking that it is a non-null plain object rather than an array, primitive, or null) before accessing properties on it.


1. Basic Safe JSON Parsing with try...catch

Wrap JSON.parse() in a try...catch block and validate that the input is a string so invalid inputs return a predictable fallback instead of throwing unhandled exceptions:

// Safely parse a JSON string, returning fallbackValue when input is invalid JSON
function safeJsonParse(jsonString, fallbackValue = null) {
  if (typeof jsonString !== "string") {
    return fallbackValue;
  }

  const trimmed = jsonString.trim();
  if (trimmed.length === 0) {
    return fallbackValue;
  }

  try {
    return JSON.parse(trimmed);
  } catch (err) {
    if (err instanceof SyntaxError) {
      return fallbackValue;
    }
    throw err;
  }
}

// Example usage:
const validObj = safeJsonParse('{"role":"editor","retries":3}', {});
const brokenJson = safeJsonParse("{role: 'editor', bad json}", null);

console.log(validObj);   // { role: "editor", retries: 3 }
console.log(brokenJson); // null
  • Catch SyntaxError intentionally: Invalid JSON strings always throw a SyntaxError, so catching it lets you degrade gracefully to a fallback value.
  • Reject empty or non-string inputs early: Calling JSON.parse("") throws a SyntaxError, and passing non-strings like undefined or numbers can coerce unexpectedly.

2. Validating That the Parsed Result Is an Object

Valid JSON can represent objects, arrays, strings, numbers, booleans, or null—so '["a","b"]' or '123' or 'null' will parse without throwing even when your code expects a key-value object:

// Ensure the parsed JSON value is a non-null plain object (not an array or primitive)
function parseJsonObject(jsonString, fallbackObj = {}) {
  const parsed = safeJsonParse(jsonString, null);

  const isPlainObject =
    parsed !== null &&
    typeof parsed === "object" &&
    !Array.isArray(parsed);

  return isPlainObject ? parsed : fallbackObj;
}

// Example usage:
console.log(parseJsonObject('{"theme":"dark"}', {})); // { theme: "dark" }
console.log(parseJsonObject('[1, 2, 3]', {}));        // {} (array rejected)
console.log(parseJsonObject('null', {}));             // {} (null rejected)
  • Arrays pass typeof === "object": Always check !Array.isArray(parsed) and parsed !== null when requiring an object map.
  • Check required fields downstream: Even when a JSON object parses cleanly, verify expected keys or types before using nested properties.

3. Using a reviver Function for Dates and Custom Transformations

JSON.parse(text, reviver) accepts an optional second reviver(key, value) callback that runs bottom-up on every parsed property, which is useful for reviving ISO date strings or filtering unexpected keys:

// Parse JSON and convert matching ISO timestamp strings into Date instances
function parseJsonWithDates(jsonString, fallbackValue = null) {
  return safeJsonParse(
    jsonString,
    fallbackValue
  ) === fallbackValue && typeof jsonString === "string" && jsonString.trim().length > 0
    ? (() => {
        try {
          return JSON.parse(jsonString, (key, value) => {
            if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
              const date = new Date(value);
              return Number.isNaN(date.getTime()) ? value : date;
            }
            return value;
          });
        } catch {
          return fallbackValue;
        }
      })()
    : safeJsonParse(jsonString, fallbackValue);
}

// Example usage:
const rawEvent = '{"id":42,"createdAt":"2026-11-29T09:20:00.000Z"}';
const eventData = parseJsonWithDates(rawEvent);
console.log(eventData?.createdAt instanceof Date); // true
  • JSON has no native Date literal: Dates serialized with JSON.stringify() become strings, so a reviver (or explicit new Date(...) conversion) restores Date objects when needed.
  • Avoid eval(): Never use eval() or new Function() to parse JSON or object literals—JSON.parse() inside try...catch is safer and faster.

TL;DR: Wrap JSON.parse(str) in try...catch to return a fallback value on SyntaxError, and guard parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) when you specifically expect a plain object.