Safe JSON Parse (Fallback on Error)
Arguments
text: string —The JSON string to parse. fallback: any —Value to return when parsing fails. Defaults to null.
Returns
any — Solution idea
Guard the input type, then try JSON.parse in a try/catch. On any error, return the fallback. Keep the behavior predictable so tests can cover invalid inputs and boundary cases.
safeJsonParse('{"ok":true}') // => { ok: true }
safeJsonParse('not json', []) // => []
safeJsonParse(42, { ok: false }) // => { ok: false }Solution
Overview
Guard the input type, then try JSON.parse in a try/catch. On any error, return the fallback. Keep the behavior predictable so tests can cover invalid inputs and boundary cases.
Approach: Guard + try/catch
Steps:
1) If text is not a string, return fallback.
2) Attempt JSON.parse.
3) On error, return fallback.
Complexity: O(n) time for parsing, O(1) extra space.
export default function safeJsonParse(text, fallback = null) {
if (typeof text !== 'string') return fallback;
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
export default function safeJsonParse(text: string, fallback: any = null): any {
if (typeof text !== 'string') return fallback;
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
Notes & Pitfalls
Assuming JSON.parse always returns an object (it can return numbers, strings, booleans, or null). Catching errors but returning undefined, which makes tests ambiguous. Parsing non-strings without guarding can throw or behave unexpectedly.
Valid primitives like '0', 'true', and 'null' should parse correctly. Whitespace around JSON is valid and should parse. Invalid JSON should always return the fallback without throwing.
Type guards before parsing. Deterministic fallback behavior for tests. Focused unit tests per edge case.
Common mistakes on this challenge
safeJsonParse fallback behavior is inconsistent
This helper should parse valid JSON and return fallback on parse/type failure. Return fallback immediately when input is not a string. Wrap JSON.parsein try/catch and return fallback on exceptions.Use nullas default fallback when fallback argument is omitted.
Resources
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.