Safe JSON Parse
VerifiedParses JSON without throwing and returns a typed { ok, value | error } result.
- json
- parse
- error-handling
- result
Install
npx shadcn@latest add https://quicksnip.dev/r/safe-json-parse.jsonCode
export type ParseResult<T> = { ok: true; value: T } | { ok: false; error: Error };
/** Parses JSON without throwing. Returns a result object you can branch on. */
export function safeJsonParse<T = unknown>(text: string): ParseResult<T> {
try {
return { ok: true, value: JSON.parse(text) as T };
} catch (error) {
return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };
}
}Usage
const result = safeJsonParse<Config>(text);
if (result.ok) use(result.value);
else console.error(result.error);