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'); // nullHints (3)
- Wrap JSON.parse in a try-catch block.
- If parsing succeeds, return the parsed result.
- If an error is thrown, return the fallback value.
Topics
- Utility Functions
Asked at
Amazon · Shopify · Stripe
