Skip to content

safeParse

Parses JSON permissively like parse — strict JSON, JSONC (HuJSON, JWCC) and JSON5 — but returns null (or fallback) instead of throwing on invalid input.

Accepts / rejects: exactly what parse does — see there for the full list.

On invalid input: returns fallback when one is given — even undefined, which is told apart from an omitted argument — and null otherwise. Never throws.

Available since v3.1.3

import { safeParse } from '@helpers4/json';
// or, from the all-in-one package (same code, one install):
import { safeParse } from 'helpers4/json';
safeParse<T = unknown>(text: string): T | null
ParameterTypeDescription
textstringThe JSON, JSONC or JSON5 text to parse

T | null — The parsed value typed as T, or null on invalid input (pass a fallback to get it instead)

Same parsing as parse, but returns null on invalid input.

safeParse('{"a": 1, /* note */}') // => { a: 1 }
safeParse('{a: }')                // => null

Pass a fallback to get a usable value even when the file is broken.

safeParse('{ broken', {})
// => {}

View source on GitHub