es-toolkit
es-toolkit copied to clipboard
feat(safeJSONParse): add safe JSON parsing utility
Description
This PR introduces a new safeJSONParse utility that provides a non-throwing wrapper around JSON.parse, complementing the existing isJSON predicate.
The goal is to keep validation and transformation clearly separated while giving consumers a type-safe way to parse JSON strings.
Changes
-
Added
safeJSONParse<T = unknown>(value: unknown): T | nullutility- Returns the parsed value when
valueis a string containing valid JSON - Returns
nullwhenvalueis not a string or when parsing fails - Mirrors
JSON.parsesemantics (e.g."null"→null) while never throwing
- Returns the parsed value when
-
Implemented comprehensive runtime tests for
safeJSONParse- Covers primitives, objects, arrays, nested structures, empty objects/arrays, and large numbers
- Verifies failure cases for invalid JSON strings and non-string inputs
- Ensures
"null"input is handled as a valid JSON string whose parsed value isnull
-
Added type-level tests using
expectTypeOf- Confirms that the generic parameter
Tis respected (T | null) - Verifies narrowing behavior after
nullchecks - Asserts the default generic (
T = unknown) when no type argument is provided
- Confirms that the generic parameter
-
Documented
safeJSONParsein a dedicated MDX page- Usage examples with valid/invalid JSON strings and non-string inputs
- Demonstrates generic usage with typed shapes (e.g.
User) - Shows how to combine
safeJSONParsewithisJSONfor clearer validation + parsing flows
Motivation
- Avoid duplicating
try { JSON.parse(...) } catch { ... }patterns across the codebase - Provide a clear separation of concerns:
isJSON(value)→ “Is this a valid JSON string?” (pure validation)safeJSONParse(value)→ “Safely parse this JSON string into a value” (transformation)
- Improve ergonomics and type safety when dealing with unknown or loosely-typed inputs
- Align JSON-related utilities under a consistent API surface, where predicates live in the predicate category and non-throwing helpers live in the utility category