parseJSON
Problem
You need to parse JSON from localStorage or an API without crashing on malformed input, and want a typed fallback for the error case.
Solution
Use parseJSON(json, options?) to return the parsed value or a fallback when parsing fails. It accepts string | null | undefined.
ts
import { parseJSON } from '@vielzeug/arsenal';
const raw = localStorage.getItem('settings');
const settings = parseJSON(raw, { fallback: { theme: 'light' } });
// returns parsed object or { theme: 'light' } on failureWith a validator
ts
import { parseJSON } from '@vielzeug/arsenal';
import { s } from '@vielzeug/spell';
const Schema = s.object({ theme: s.string() });
const settings = parseJSON(raw, {
fallback: { theme: 'light' },
validator: (v) => Schema.safeParse(v).ok,
});Pitfalls
- Without
fallback, returnsundefinedon failure — the return type includesundefined. null/undefinedinput immediately returnsfallbackwithout callingJSON.parse.- The JSON string
"null"parses tonull(notfallback) — only the input beingnulltriggers the fallback.