The JavaScript value to serialize. While any value is accepted, the property filtering only applies to objects and nested objects.
Optional
propertiesToBeSelected: 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.
Optional
space: string | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10Optional formatting parameter:
A Result<string, string>
containing:
Result.ok(jsonString)
with only selected propertiesResult.err(errorMessage)
describing the serialization errorconst 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));
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.