The value to serialize. Can be any JavaScript value: objects, arrays, primitives, null, etc.
Optionalreplacer: (string | number)[] | ReplacerOptional replacer function or array of keys to include (same as JSON.stringify).
Optionalspace: string | numberOptional indentation: a string (e.g., "\t") or number of spaces (e.g., 2) for pretty-printing.
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() callsconst 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]"
// }
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 faultytoJSON()implementations.This function sanitizes the input by:
"[Circular]""[Throws: <message>]"toJSON()methods, falling back to error placeholders on throwThe resulting structure is then passed to
JSON.stringify, preserving standard replacer and space behavior.