Code Lab

Safe JSON.parse

EasyErrors4 min

Write a function safeParse(text, fallback). If text is valid JSON, return the parsed value. If the string cannot be parsed, return fallback.

Examples

safeParse('{"id":1}', null)

Returns { id: 1 }

safeParse('{id:1}', null)

Returns null

In JSON a key must be in double quotes.
safeParse('0', 10)

Returns 0

`0` is valid JSON too.

Source

Loading the editor...
  1. InputsafeParse('{"id":1}', null)
    Expected{ id: 1 }
  2. InputsafeParse('{id:1}', null)
    Expectednull
  3. InputsafeParse('0', 10)
    Expected0

Hidden tests run on Submit.