Fast Safe Stringify

2.1.1 · active · verified Sun Apr 19

fast-safe-stringify is a utility library designed for safely and quickly serializing JavaScript objects into JSON strings. It provides a robust alternative to the native `JSON.stringify`, specifically excelling at gracefully handling circular references within objects without throwing a `TypeError`. Instead, it intelligently replaces circular structures with a `[Circular]` string or `[...]` when configured limits are reached. The current stable version is 2.1.1, with recent updates (v2.1.0 and v2.1.1) introducing and refining `depthLimit` and `edgesLimit` options to prevent excessive recursion in complex objects. The library also offers a `stableStringify` function, which guarantees a deterministic output order for object keys, enhancing reproducibility. It is actively maintained and ships with TypeScript type definitions, making it suitable for modern JavaScript and TypeScript environments where predictable serialization of potentially self-referential data structures is crucial, such as in logging or API responses.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates `safeStringify` and `stableStringify` handling circular references and optional depth limits.

import safeStringify, { stableStringify } from 'fast-safe-stringify';

const obj = { a: 1, b: 0 };
obj.circular = obj;
obj.anotherRef = obj;

console.log('Original object with circular refs:', obj);

// Using fast-safe-stringify to handle circular references
const safeSerialized = safeStringify(obj);
console.log('\nSafe Stringify Output (non-deterministic key order):', safeSerialized);
// Expected: '{"a":1,"b":0,"circular":"[Circular]","anotherRef":"[Circular]"}'

// Using stableStringify for deterministic output order
const stableSerialized = stableStringify(obj);
console.log('Stable Stringify Output (deterministic key order):', stableSerialized);
// Expected: '{"a":1,"b":0,"anotherRef":"[Circular]","circular":"[Circular]"}'

const deepCircular = { level1: { level2: {} } };
deepCircular.level1.level2.parent = deepCircular;

console.log('\nSafe Stringify with depth limit (default is MAX_SAFE_INTEGER):');
const limitedSerialized = safeStringify(deepCircular, null, 2, { depthLimit: 2 });
console.log(limitedSerialized);
// Expected: '{\n  "level1": {\n    "level2": "[...]"\n  }\n}'

view raw JSON →