Skip to content
SDETRole
SDETRole

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 }, where value is the parsed result. null, 0 and false are valid results.
  • On failure return { ok: false, error }, where error is a non-empty string message.
  • Never throw, whatever is passed in.
  • Treat any non-string input (such as undefined or 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.

Type to search across SDETRole.

Full-text search by Pagefind · runs in your browser Open search page →