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
safeParse('0', 10)Returns 0
Loading the editor...
- Input
safeParse('{"id":1}', null)Expected{ id: 1 } - Input
safeParse('{id:1}', null)Expectednull - Input
safeParse('0', 10)Expected0
Hidden tests run on Submit