ts-data-forge
    Preparing search index...

    Function stringifySelected

    • Safely converts a JavaScript value to a JSON string, including only the specified properties.

      This function provides selective serialization by allowing you to specify exactly which object properties should be included in the resulting JSON. It's useful for creating filtered or minimal representations of objects, such as for API responses or logging.

      Parameters

      • value: unknown

        The JavaScript value to serialize. While any value is accepted, the property filtering only applies to objects and nested objects.

      • OptionalpropertiesToBeSelected: readonly (string | number)[]

        Optional array of property names (strings) and array indices (numbers) to include in the serialization. If provided, only these properties will appear in the output JSON. If undefined, all properties are included.

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

        Optional formatting parameter:

        • 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) with only selected properties
      • On failure: Result.err(errorMessage) describing the serialization error
      const user = {
      id: 1,
      name: 'Charlie',
      email: 'charlie@example.com',
      password: 'secret123',
      role: 'admin',
      };

      // Select only safe properties to serialize
      const safeJson = Json.stringifySelected(user, ['id', 'name', 'role']);

      assert.ok(Result.isOk(safeJson));
      if (Result.isOk(safeJson)) {
      const parsed: unknown = JSON.parse(safeJson.value);
      assert.deepStrictEqual(parsed, {
      id: 1,
      name: 'Charlie',
      role: 'admin',
      });
      assert.ok(!safeJson.value.includes('password'));
      assert.ok(!safeJson.value.includes('email'));
      }

      // With formatting
      const formatted = Json.stringifySelected(user, ['id', 'name'], 2);
      assert.ok(Result.isOk(formatted));