EasyJavaScriptTypeScript

Parse JSON Safely

Node.jsReliability

The function below parses a JSON string, but it will throw a `SyntaxError` when the input is invalid — crashing the caller with an unhandled exception.

The bug: JSON.parse throws on malformed input. In a server context, one bad request body can take down your entire request handler.

Your task: fix solve(jsonString, fallback) so that:

  • It returns the parsed value on valid JSON.
  • It returns fallback (never throws) on any invalid input.
solve('{"a":1}', null)  // → { a: 1 }
solve('not json',  null) // → null  (no throw)
solve('',          42)   // → 42

Sample tests

Test #1Valid JSON object
Input: ["{\"a\":1}",null]
Output: {"a":1}
Test #2Invalid JSON — returns fallback
Input: ["not json",null]
Output: null
Test #3Valid JSON array
Input: ["[1,2,3]",[]]
Output: [1,2,3]
Test #4Empty string — returns fallback
Input: ["","default"]
Output: "default"