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.
Optional
replacer: (this: unknown, key: string, val: unknown) => unknownOptional 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.
Optional
space: string | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10Optional parameter for formatting the output JSON:
A Result<string, string>
containing:
Result.ok(jsonString)
where jsonString
is the serialized
JSONResult.err(errorMessage)
where errorMessage
describes the
errorconst 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'));
}
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 aResult
type, allowing you to handle serialization errors gracefully (such as circular references or BigInt values).