Safe JSON Parse

EasyUtility Functions5 min4 tests

Implement a safeJsonParse function that safely parses a JSON string, returning a fallback value if parsing fails.

Requirements

  • Attempt to parse the input string as JSON
  • If parsing succeeds, return the parsed value
  • If parsing throws, return the provided fallback value
  • Handle any input gracefully (null, undefined, invalid strings)

Example

safeJsonParse('{"a":1}', {});    // { a: 1 }
safeJsonParse('invalid', {});    // {}
safeJsonParse('null', 'fallback'); // null
Hints (3)
  1. Wrap JSON.parse in a try-catch block.
  2. If parsing succeeds, return the parsed result.
  3. If an error is thrown, return the fallback value.

Topics

  • Utility Functions

Asked at

Amazon · Shopify · Stripe

Join Us
blur