Safe JSON Parse (Fallback on Error)

easy
By FrontendAtlas Editorial · Updated Oct 10, 2026
Implement safeJsonParse(text, fallback = null) to safely parse JSON. It should return the parsed value for valid JSON strings and the fallback for invalid JSON or non-string inputs. This is a common edge-case strategy for parsing unknown inputs.

Arguments

  • text: string — The JSON string to parse.
  • fallback: any — Value to return when parsing fails. Defaults to null.

Returns

any — Parsed JSON value or the fallback.

Solution idea

Guard the input type, then try JSON.parse in a try/catch. On any error, return the fallback. Keep the behavior predictable so tests can cover invalid inputs and boundary cases.

Examples
safeJsonParse('{"ok":true}') // => { ok: true }

safeJsonParse('not json', []) // => []

safeJsonParse(42, { ok: false }) // => { ok: false }