ts-data-forge
    Preparing search index...

    Function stringify

    • Safely converts a JavaScript value to a JSON string without throwing exceptions.

      This function provides type-safe JSON stringification by wrapping the native JSON.stringify in a Result type, allowing you to handle serialization errors gracefully (such as circular references or BigInt values).

      Parameters

      • value: unknown

        The JavaScript value to serialize. Can be any value that JSON.stringify accepts: primitives, objects, arrays. Non-serializable values (functions, undefined, symbols) will be omitted or converted to null according to JSON.stringify behavior.

      • Optionalreplacer: (this: unknown, key: string, val: unknown) => unknown

        Optional function that transforms values during serialization. Called for each key-value pair. Should return the value to be serialized, or undefined to omit the property from the result.

      • Optionalspace: string | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10

        Optional parameter for formatting the output JSON:

        • Number (1-10): Number of spaces to indent each level
        • String: String to use for indentation (first 10 characters)
        • Undefined/null: No formatting (compact output)

      Returns Result<string, string>

      A Result<string, string> containing:

      • On success: Result.ok(jsonString) where jsonString is the serialized JSON
      • On failure: Result.err(errorMessage) where errorMessage describes the error
      const data = { name: 'Bob', age: 25, active: true };

      // Basic stringify
      const basic = Json.stringify(data);
      assert.ok(Result.isOk(basic));
      if (Result.isOk(basic)) {
      assert(basic.value === '{"name":"Bob","age":25,"active":true}');
      }

      // With formatting
      const formatted = Json.stringify(data, undefined, 2);
      assert.ok(Result.isOk(formatted));

      // With replacer
      const filtered = Json.stringify(data, (key, value) => {
      if (key === 'age') return undefined; // omit age field
      return value;
      });

      assert.ok(Result.isOk(filtered));
      if (Result.isOk(filtered)) {
      assert.ok(!filtered.value.includes('age'));
      }