Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Safe JSON Parse

Asynchronous JavaScripteasy

Course · Section 16: Asynchronous JavaScript: Promises, Async/Await, and AJAX · Lecture 275: Error Handling With try...catch

Implement `safeParse(s)` returning the parsed JSON value, or `null` if `s` is not valid JSON.

Sample tests

Input: safeParse("{\"a\":1}")
Output: {"a":1}
Input: safeParse("nope")
Output: null

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Letting the parse error propagate instead of catching it.

Learning resources

  • MDN: try...catch
Approach & explanation (try first)

try/catch around JSON.parse returns the parsed value or null for invalid JSON.

Loading...
⌘/Ctrl + Enter

Run your code to see results.