← Back to utilities
json

safe-parse

Safely parses a JSON string, returning undefined if parsing fails. Provides error-safe JSON parsing without throwing exceptions. Useful when working with untrusted input or when you want to handle parsing failures gracefully rather than with try-catch blocks.

Installation

npx fragmen add json/safe-parse

Source Code

/**
 * Safely parses a JSON string, returning undefined if parsing fails.
 *
 * Provides error-safe JSON parsing without throwing exceptions. Useful when
 * working with untrusted input or when you want to handle parsing failures
 * gracefully rather than with try-catch blocks.
 *
 * @tags pure, validation
 * @param {string} str The JSON string to parse.
 * @returns {T | undefined} The parsed value with the specified type, or undefined if parsing fails.
 *
 * @example
 * ```typescript
 * const validJson = '{"name": "John", "age": 30}';
 * const result = safeParse<{name: string, age: number}>(validJson);
 * // Result: { name: "John", age: 30 }
 *
 * const invalidJson = '{name: "John"}'; // Missing quotes
 * const failed = safeParse(invalidJson);
 * // Result: undefined
 *
 * const config = safeParse(userInput) ?? { theme: 'light', lang: 'en' };
 * ```
 */
export function safeParse<T = unknown>(str: string): T | undefined {
  try {
    return JSON.parse(str) as T;
  } catch {
    return undefined;
  }
}

Examples

const validJson = '{"name": "John", "age": 30}';
const result = safeParse<{name: string, age: number}>(validJson);
// Result: { name: "John", age: 30 }

const invalidJson = '{name: "John"}'; // Missing quotes
const failed = safeParse(invalidJson);
// Result: undefined

const config = safeParse(userInput) ?? { theme: 'light', lang: 'en' };

Related Utilities

is-falsy

boolean

Checks if a value is falsy. Returns true for JavaScript falsy values: false, 0, -0, 0n, "", null, undefined, and NaN. Useful for type-safe falsy checks and filtering operations.

#pure#validation#type-checking

is-truthy

boolean

Checks if a value is truthy. Returns true for all JavaScript truthy values (anything that is not falsy). Complementary function to isFalsy, useful for filtering and validation.

#pure#validation#type-checking

has-path

object

Checks if a nested property path exists in an object. Safely traverses nested object properties using a dot-notation path string or an array of keys. Returns true if the path exists (even if the final value is undefined), false if any part of the path is missing.

#pure#validation

is-equal

validation

Deep comparison of two values for equality. Recursively compares objects, arrays, dates, and primitives for deep equality. Handles circular references, special objects (Date, RegExp, Map, Set), and all primitive types. Useful for comparing complex data structures.

#validation#pure

chunk

array

Splits an array into chunks of a specified size. Creates a new array containing subarrays (chunks) of the original array, each with a maximum length of the specified size. The last chunk may contain fewer elements if the array length is not evenly divisible by the chunk size.

#pure#array-manipulation

compact

array

Removes falsy values from an array. Creates a new array with all falsy values removed. Falsy values are: false, null, 0, "", undefined, and NaN. This is useful for cleaning arrays and ensuring only truthy values remain.

#pure#array-manipulation

Quick Actions

Estimated size:1017 B

Tags

Parameters

strstring

The JSON string to parse.

Returns

T | undefined

The parsed value with the specified type, or undefined if parsing fails.