fast-safe-stringify
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
Fast-safe-stringify is a performant and safe way to serialize JavaScript objects. Unlike the common JSON.stringify()
, it handles circular structures gracefully instead of throwing an error, making it an excellent alternative for serializing complex JavaScript objects. In most cases, it successfully resolves circular structures, and only in complex scenarios, such as those involving proxies, might it return an error string. Furthermore, it also provides a deterministic ("stable") version that offers the same benefits, while ensuring the output order remains consistent.
Fast-safe-stringify is utilized in the same way as JSON.stringify()
. First, install it in your Node.js project using npm or yarn. Here's an example of how you can use fast-safe-stringify in your code.
// Import the package
const safeStringify = require('fast-safe-stringify');
// Make a circular object
const o = { a: 1 };
o.o = o;
// Use safeStringify instead of JSON.stringify
console.log(safeStringify(o));
// The output will be:
// {"a":1,"o":"[Circular]"}
The function stringify
accepts four arguments: value
, replacer
, space
, and options
. The value
is what you want to stringify. The replacer
function, if provided, alters the behavior of the stringification process. space
is used for adding indentation, and options
can be used for setting depth and edge limits.
Here is another example with these additional parameters:
// Define a replacer function
function replacer(key, value) {
// Remove the circular structure
if (value === '[Circular]') {
return;
}
return value;
}
// Set options
const options = {
depthLimit: Number.MAX_SAFE_INTEGER,
edgesLimit: Number.MAX_SAFE_INTEGER
};
// Use safeStringify with all parameters
const serialized = safeStringify(o, replacer, 2, options);
console.log(serialized);
// The output will be:
// {
// "a": 1
// }
Fast-safe-stringify's documentation is located within its README file on GitHub. In this file, you'll find comprehensible information about all the capabilities of the library, including its usage, differences and exceptions compared to JSON.stringify()
, and its performance benchmarks.