Survive Malformed JSON

Easy ⏱ 8 min 88% acceptance ★★★★☆ 4.2
Write parse_or_none(raw) returning the parsed object, or None when raw is not valid JSON — catching json.JSONDecodeError specifically, not bare Exception.

Examples

Example 1
Input
parse_or_none('[1, 2]')
Output
[1, 2]
Explanation

Valid JSON parses normally.

Example 2
Input
parse_or_none('{oops}')
Output
None
Explanation

The decode error is absorbed.

Constraints

  • Catch json.JSONDecodeError only.
  • Return the parsed value otherwise.

Topics

JSONJSONDecodeError

Companies

AkamaiCloudflareFastly

Hints

Hint 1

JSONDecodeError lives on the json module.

Hint 2

One try/except around loads.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.