es-toolkit icon indicating copy to clipboard operation
es-toolkit copied to clipboard

feat(safeJSONParse): add safe JSON parsing utility

Open Yeom-JinHo opened this issue 1 month ago • 4 comments

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 | null utility

    • Returns the parsed value when value is a string containing valid JSON
    • Returns null when value is not a string or when parsing fails
    • Mirrors JSON.parse semantics (e.g. "null"null) while never throwing
  • 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 is null
  • Added type-level tests using expectTypeOf

    • Confirms that the generic parameter T is respected (T | null)
    • Verifies narrowing behavior after null checks
    • Asserts the default generic (T = unknown) when no type argument is provided
  • Documented safeJSONParse in 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 safeJSONParse with isJSON for 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

Yeom-JinHo avatar Nov 14 '25 12:11 Yeom-JinHo