TS-Scribe - v0.6.2
    Preparing search index...

    Function safeJsonParse

    • Safely parses a JSON string, returning a fallback value if parsing fails.

      Type Parameters

      • T

        The expected return type after parsing.

      Parameters

      • text: string

        The JSON string to parse.

      • fallback: T

        The fallback value to return if parsing fails.

      • Optionaloptions: {
            callback?: (error: unknown) => void;
            logError?: boolean;
            reviver?: (this: any, key: string, value: any) => any;
        }

        Optional settings to customize parsing behavior.

        • Optionalcallback?: (error: unknown) => void

          Optional callback invoked when parsing fails. Receives the error object.

        • OptionallogError?: boolean

          If true, logs the error and input string to the console.

        • Optionalreviver?: (this: any, key: string, value: any) => any

          Optional reviver function passed to JSON.parse.

      Returns T

      The parsed object if successful, otherwise the fallback value.

      const jsonString = '{ "age": 30 }';
      const result = safeJsonParse(jsonString, {}, {
      callback: (err) => console.warn("Parse failed:", err),
      logError: true,
      });
      // result => { age: 30 }
      const badJson = '{ invalid JSON }';
      const result = safeJsonParse(badJson, { name: "Default" });
      // result => { name: "Default" }