Safe JSON parse
intermediate Error handling Challenge 5 of 18
Write safeJsonParse(text), which parses JSON without ever throwing. Use it when a response body or a fixture file might not be valid JSON.
Requirements
- On success return
{ ok: true, value }, wherevalueis the parsed result.null,0andfalseare valid results. - On failure return
{ ok: false, error }, whereerroris a non-empty string message. - Never throw, whatever is passed in.
- Treat any non-string input (such as
undefinedor a number) as a failure.
Expected output
safeJsonParse('{"id":1}') → { ok: true, value: { id: 1 } } safeJsonParse('{id:1}') → { ok: false, error: '<parser message>' } safeJsonParse(undefined) → { ok: false, error: 'Input must be a string' }
Test cases (6)
- ○parses a valid object
- ○returns ok false for invalid JSON
- ○null is valid JSON
- ○empty string is invalid
- ○never throws for non-string input
- ○failure objects have no value property
solution.jsExecutes in your browser
Ctrl/⌘ + Enter to run tests · your code is saved in this browser
Results
Run the tests to see results here.