@bnidev/js-utils
    Preparing search index...

    Function sanitizeJson

    • Safely parses a JSON string and optionally validates the resulting object.

      Type Parameters

      • T = unknown

      Parameters

      • input: string

        The input JSON string to parse.

      • Optionalvalidate: (obj: unknown) => obj is T

        An optional type guard function to validate the parsed object.

      Returns { error?: Error; success: boolean; value: null | T }

      An object containing:

      • success: Indicates whether parsing (and validation) succeeded.
      • value: The parsed object if successful; otherwise null.
      • error: An error object if parsing failed or validation was unsuccessful.

      This utility is useful when working with dynamic or untrusted JSON data, such as user input, localStorage values, or external API responses. It prevents runtime exceptions by catching JSON.parse errors, and it provides optional runtime validation for extra safety.

      Using a type guard function enables strong typing of the return value if validation succeeds.

      // ES Module
      import { sanitizeJson } from '@bnidev/js-utils'

      // CommonJS
      const { sanitizeJson } = require('@bnidev/js-utils')
      type Person = { name: string }

      function isPerson(obj: unknown): obj is Person {
      return typeof obj === 'object' && obj !== null && 'name' in obj && typeof (obj as any).name === 'string'
      }

      const result = sanitizeJson<Person>('{"name": "Alice"}', isPerson)

      if (result.success) {
      console.log(result.value.name) // 'Alice'
      } else {
      console.error(result.error)
      }
      const result = sanitizeJson('{"foo": 123}')

      if (result.success) {
      console.log(result.value.foo) // 123
      }