Skip to content

safeJsonParse

Parses a JSON string, returning null (or a fallback) on any parse failure.

Unlike JSON.parse, this never throws. Invalid JSON strings and other parsing edge-cases resolve to null or the provided fallback.

Available since v2.0.0

import { safeJsonParse } from '@helpers4/object';
// or, from the all-in-one package (same code, one install):
import { safeJsonParse } from 'helpers4/object';
safeJsonParse<T>(input: string): T | null
ParameterTypeDescription
inputstringThe JSON string to parse.

T | null — The parsed value typed as T, or fallback on failure.

Returns the parsed value when the input is valid JSON.

safeJsonParse<{ a: number }>('{"a":1}')
// => { a: 1 }

Returns null instead of throwing when JSON is malformed.

safeJsonParse('invalid')
// => null

Returns the provided fallback when parsing fails.

safeJsonParse('invalid', [])
// => []

View source on GitHub