easy +8 pts

Parse JSON safely

Safely parse JSON strings while handling malformed input gracefully.

Implement a function `safe_json_loads(json_string, default=None)` that attempts to parse a JSON string using Python's `json` module. If the input is not a string or is invalid JSON, the function should catch the appropriate exceptions and return the `default` value. Otherwise, it should return the parsed object. The function signature: `def safe_json_loads(json_string, default=None):` Ensure it handles all expected error cases gracefully. The function should never raise an exception.

Constraints

- Input `json_string` can be any Python object, but typically a string. - The maximum length of `json_string` is reasonable (within typical memory limits). - Complexity: O(n) based on the JSON parsing.

Example

>>> safe_json_loads('{"a": 1}')
{'a': 1}
>>> safe_json_loads('invalid json')
>>> safe_json_loads('invalid json', default=[])
[]
>>> safe_json_loads(12345, default='fallback')
'fallback'
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Catch `json.JSONDecodeError` for invalid JSON strings.
The input might not be a string—consider what exception occurs when passing a non-string to `json.loads`.
Use a single `try`/`except` block to handle both cases.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.