Skip to content
Exercise · Errors · lesson 9 of 10

Exercise: JSON or a fallback

Write a function function parseJsonOr(text, fallback, check) that parses a JSON string, passes the resulting value to the function check and returns that value. If text is not valid JSON, the function does not throw an error but returns fallback. An error thrown by check comes out of the function unchanged.

  • parseJsonOr("[1, 2]", [], () => {}) → [1, 2]
  • parseJsonOr("{ bad", "none", () => {}) → "none"
  • parseJsonOr('"hi"', 0, mustBeNumber) → throws the TypeError that mustBeNumber threw: it checks that the value is a number

Constraints: text is always a string, possibly empty (which is not valid JSON); the value from valid JSON is returned even when it is null, false or 0; fallback is returned as is, without calling check.

Do not add extra imports unless the task says so explicitly.

parse-json-or.js — javascript
javascript · 4 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way