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

    Function safeJsonStringify

    • Safely serializes a JavaScript value to a JSON string, avoiding runtime errors that commonly occur with JSON.stringify, such as circular references, throwing getters, or faulty toJSON() implementations.

      This function sanitizes the input by:

      • Replacing circular references with the string "[Circular]"
      • Replacing values from throwing property access (e.g., faulty getters) with "[Throws: <message>]"
      • Safely invoking and processing toJSON() methods, falling back to error placeholders on throw

      The resulting structure is then passed to JSON.stringify, preserving standard replacer and space behavior.

      Parameters

      • data: unknown

        The value to serialize. Can be any JavaScript value: objects, arrays, primitives, null, etc.

      • Optionalreplacer: (string | number)[] | Replacer

        Optional replacer function or array of keys to include (same as JSON.stringify).

      • Optionalspace: string | number

        Optional indentation: a string (e.g., "\t") or number of spaces (e.g., 2) for pretty-printing.

      Returns string

      A valid JSON string. Unsafe values are replaced with descriptive placeholders:

      • "[Circular]" for circular references
      • "[Throws: <message>]" for properties that throw during access or toJSON() calls
      const obj = { name: "Alice" };
      obj.self = obj; // circular
      Object.defineProperty(obj, "secret", {
      get() { throw new Error("Access denied"); }
      });

      const result = safeStringify(obj, null, 2);
      console.log(result);
      // {
      // "name": "Alice",
      // "self": "[Circular]",
      // "secret": "[Throws: Access denied]"
      // }