safe-stable-stringify vs fast-safe-stringify vs json-stringify-safe vs safe-json-stringify
JSON Stringify Libraries
safe-stable-stringifyfast-safe-stringifyjson-stringify-safesafe-json-stringifySimilar Packages:

JSON Stringify Libraries

These libraries are designed to safely stringify JavaScript objects into JSON format while handling circular references and ensuring that the output is valid JSON. They provide various features to enhance performance, safety, and stability when converting complex objects to JSON, making them essential tools for developers who need to serialize data without encountering errors or losing information.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
safe-stable-stringify38,167,67424530.7 kB32 years agoMIT
fast-safe-stringify0357-95 years agoMIT
json-stringify-safe0555-711 years agoISC
safe-json-stringify058-38 years agoMIT

Feature Comparison: safe-stable-stringify vs fast-safe-stringify vs json-stringify-safe vs safe-json-stringify

Performance

  • safe-stable-stringify:

    safe-stable-stringify may not be the fastest option due to its focus on maintaining property order and stability in the output. It is best used in scenarios where consistent output is more important than raw speed.

  • fast-safe-stringify:

    fast-safe-stringify is designed for high performance, making it one of the fastest options available for stringifying objects. It utilizes optimized algorithms to minimize the overhead associated with serialization, making it suitable for performance-critical applications.

  • json-stringify-safe:

    json-stringify-safe provides a reliable performance but is not as fast as fast-safe-stringify. It focuses on safety rather than speed, ensuring that circular references are handled without throwing errors, which may slightly impact performance in complex scenarios.

  • safe-json-stringify:

    safe-json-stringify strikes a balance between performance and safety. It is optimized for general use cases and provides adequate speed while ensuring that circular references are managed appropriately during serialization.

Circular Reference Handling

  • safe-stable-stringify:

    safe-stable-stringify handles circular references similarly by replacing them with a placeholder, ensuring that the serialization process does not fail. This feature is crucial for maintaining stability in the output.

  • fast-safe-stringify:

    fast-safe-stringify effectively handles circular references by replacing them with a placeholder. This allows the serialization process to continue without throwing errors, making it a robust choice for complex object graphs.

  • json-stringify-safe:

    json-stringify-safe is specifically designed to handle circular references by safely replacing them with a string value, preventing serialization errors. It is a straightforward solution for developers who need to manage circular references easily.

  • safe-json-stringify:

    safe-json-stringify also manages circular references by replacing them with a specified value, allowing for flexible handling of complex objects. This feature is essential for applications that frequently deal with nested structures.

Output Consistency

  • safe-stable-stringify:

    safe-stable-stringify guarantees stable output by maintaining the order of properties in the serialized JSON. This is particularly useful for testing, logging, and scenarios where output consistency is critical.

  • fast-safe-stringify:

    fast-safe-stringify does not guarantee output consistency in terms of property order, which may lead to different outputs for the same input. This is acceptable in scenarios where performance is prioritized over output predictability.

  • json-stringify-safe:

    json-stringify-safe provides consistent output for simple objects but does not guarantee property order for complex nested structures. It is suitable for general use cases where output consistency is not a primary concern.

  • safe-json-stringify:

    safe-json-stringify ensures that the output is consistent for the same input objects, making it a reliable choice for applications that require predictable serialization results.

Customization Options

  • safe-stable-stringify:

    safe-stable-stringify offers customization options for handling circular references and property serialization, making it suitable for developers who need precise control over the output.

  • fast-safe-stringify:

    fast-safe-stringify offers limited customization options, focusing primarily on performance. Developers may find it less flexible for specific serialization needs compared to other libraries.

  • json-stringify-safe:

    json-stringify-safe provides basic customization options, allowing developers to specify a replacer function to control how objects are serialized. This makes it adaptable for various use cases without being overly complex.

  • safe-json-stringify:

    safe-json-stringify allows for more customization compared to others, enabling developers to define how specific properties should be handled during serialization. This flexibility is beneficial for complex data structures.

Ease of Use

  • safe-stable-stringify:

    safe-stable-stringify is also easy to use, with clear API documentation. Its focus on stable output may require developers to understand the implications of property order in their data structures.

  • fast-safe-stringify:

    fast-safe-stringify is straightforward to use, requiring minimal setup. However, its focus on performance may come at the cost of some advanced features that developers might expect.

  • json-stringify-safe:

    json-stringify-safe is very easy to integrate into existing projects, making it a popular choice for developers looking for a quick and safe solution for JSON serialization.

  • safe-json-stringify:

    safe-json-stringify is user-friendly and provides clear documentation, making it accessible for developers of all skill levels. Its balance of safety and performance makes it a versatile option.

How to Choose: safe-stable-stringify vs fast-safe-stringify vs json-stringify-safe vs safe-json-stringify

  • safe-stable-stringify:

    Use safe-stable-stringify when you need consistent output for the same input objects, especially in cases where the order of properties matters. This library ensures that the output is stable and predictable, making it ideal for testing and logging purposes.

  • fast-safe-stringify:

    Choose fast-safe-stringify if performance is your top priority and you need a library that can handle circular references efficiently. It is optimized for speed and is ideal for applications where serialization speed is critical.

  • json-stringify-safe:

    Select json-stringify-safe if you require a straightforward solution for safely stringifying objects with circular references. It is easy to use and integrates well with existing codebases, making it suitable for general-purpose use.

  • safe-json-stringify:

    Opt for safe-json-stringify if you need a library that provides a balance between safety and performance while also allowing for customization of the serialization process. It is useful for applications that require specific handling of object properties during serialization.

README for safe-stable-stringify

safe-stable-stringify

Safe, deterministic and fast serialization alternative to JSON.stringify. Zero dependencies. ESM and CJS. 100% coverage.

Gracefully handles circular structures and bigint instead of throwing.

Optional custom circular values, deterministic behavior or strict JSON compatibility check.

stringify(value[, replacer[, space]])

The same as JSON.stringify.

  • value {any}
  • replacer {string[]|function|null}
  • space {number|string}
  • Returns: {string}
const stringify = require('safe-stable-stringify')

const bigint = { a: 0, c: 2n, b: 1 }

stringify(bigint)
// '{"a":0,"b":1,"c":2}'
JSON.stringify(bigint)
// TypeError: Do not know how to serialize a BigInt

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

stringify(circular)
// '{"a":0,"b":1,"circular":"[Circular]"}'
JSON.stringify(circular)
// TypeError: Converting circular structure to JSON

stringify(circular, ['a', 'b'], 2)
// {
//   "a": 0,
//   "b": 1
// }

stringify.configure(options)

  • bigint {boolean} If true, bigint values are converted to a number. Otherwise they are ignored. Default: true.
  • circularValue {string|null|undefined|ErrorConstructor} Defines the value for circular references. Set to undefined, circular properties are not serialized (array entries are replaced with null). Set to Error, to throw on circular references. Default: '[Circular]'.
  • deterministic {boolean|function} If true or a Array#sort(comparator) comparator method, guarantee a deterministic key order instead of relying on the insertion order. Default: true.
  • maximumBreadth {number} Maximum number of entries to serialize per object (at least one). The serialized output contains information about how many entries have not been serialized. Ignored properties are counted as well (e.g., properties with symbol values). Using the array replacer overrules this option. Default: Infinity
  • maximumDepth {number} Maximum number of object nesting levels (at least 1) that will be serialized. Objects at the maximum level are serialized as '[Object]' and arrays as '[Array]'. Default: Infinity
  • strict {boolean} Instead of handling any JSON value gracefully, throw an error in case it may not be represented as JSON (functions, NaN, ...). Circular values and bigint values throw as well in case either option is not explicitly defined. Sets and Maps are not detected as well as Symbol keys! Default: false
  • Returns: {function} A stringify function with the options applied.
import { configure } from 'safe-stable-stringify'

const stringify = configure({
  bigint: true,
  circularValue: 'Magic circle!',
  deterministic: false,
  maximumDepth: 1,
  maximumBreadth: 4
})

const circular = {
  bigint: 999_999_999_999_999_999n,
  typed: new Uint8Array(3),
  deterministic: "I don't think so",
}
circular.circular = circular
circular.ignored = true
circular.alsoIgnored = 'Yes!'

const stringified = stringify(circular, null, 4)

console.log(stringified)
// {
//     "bigint": 999999999999999999,
//     "typed": "[Object]",
//     "deterministic": "I don't think so",
//     "circular": "Magic circle!",
//     "...": "2 items not stringified"
// }

const throwOnCircular = configure({
  circularValue: Error
})

throwOnCircular(circular);
// TypeError: Converting circular structure to JSON

Differences to JSON.stringify

  1. Circular values are replaced with the string [Circular] (configurable).
  2. Object keys are sorted instead of using the insertion order (configurable).
  3. BigInt values are stringified as regular number instead of throwing a TypeError (configurable).
  4. Boxed primitives (e.g., Number(5)) are not unboxed and are handled as regular object.

Those are the only differences to JSON.stringify(). This is a side effect free variant and toJSON, replacer and the spacer work the same as with JSON.stringify().

Performance / Benchmarks

Currently this is by far the fastest known stable (deterministic) stringify implementation. This is especially important for big objects and TypedArrays.

(Dell Precision 5540, i7-9850H CPU @ 2.60GHz, Node.js 16.11.1)

simple:   simple object x 3,463,894 ops/sec ±0.44% (98 runs sampled)
simple:   circular      x 1,236,007 ops/sec ±0.46% (99 runs sampled)
simple:   deep          x 18,942 ops/sec ±0.41% (93 runs sampled)
simple:   deep circular x 18,690 ops/sec ±0.72% (96 runs sampled)

replacer:   simple object x 2,664,940 ops/sec ±0.31% (98 runs sampled)
replacer:   circular      x 1,015,981 ops/sec ±0.09% (99 runs sampled)
replacer:   deep          x 17,328 ops/sec ±0.38% (97 runs sampled)
replacer:   deep circular x 17,071 ops/sec ±0.21% (98 runs sampled)

array:   simple object x 3,869,608 ops/sec ±0.22% (98 runs sampled)
array:   circular      x 3,853,943 ops/sec ±0.45% (96 runs sampled)
array:   deep          x 3,563,227 ops/sec ±0.20% (100 runs sampled)
array:   deep circular x 3,286,475 ops/sec ±0.07% (100 runs sampled)

indentation:   simple object x 2,183,162 ops/sec ±0.66% (97 runs sampled)
indentation:   circular      x 872,538 ops/sec ±0.57% (98 runs sampled)
indentation:   deep          x 16,795 ops/sec ±0.48% (93 runs sampled)
indentation:   deep circular x 16,443 ops/sec ±0.40% (97 runs sampled)

Comparing safe-stable-stringify with known alternatives:

fast-json-stable-stringify x 18,765 ops/sec ±0.71% (94 runs sampled)
json-stable-stringify x 13,870 ops/sec ±0.72% (94 runs sampled)
fast-stable-stringify x 21,343 ops/sec ±0.33% (95 runs sampled)
faster-stable-stringify x 17,707 ops/sec ±0.44% (97 runs sampled)
json-stringify-deterministic x 11,208 ops/sec ±0.57% (98 runs sampled)
fast-safe-stringify x 21,460 ops/sec ±0.75% (99 runs sampled)
this x 30,367 ops/sec ±0.39% (96 runs sampled)

The fastest is this

The fast-safe-stringify comparison uses the modules stable implementation.

Acknowledgements

Sponsored by MaibornWolff and nearForm

License

MIT