fast-safe-stringify vs json-stringify-safe vs safe-json-stringify vs safe-stable-stringify
JSON Stringify Libraries
fast-safe-stringifyjson-stringify-safesafe-json-stringifysafe-stable-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
fast-safe-stringify28,033,589357-95 years agoMIT
json-stringify-safe0554-711 years agoISC
safe-json-stringify058-38 years agoMIT
safe-stable-stringify024130.7 kB22 years agoMIT

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

Performance

  • 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.

  • 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.

Circular Reference Handling

  • 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.

  • 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.

Output Consistency

  • 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.

  • 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.

Customization Options

  • 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.

  • 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.

Ease of Use

  • 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.

  • 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.

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

  • 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.

  • 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.

README for fast-safe-stringify

fast-safe-stringify

Safe and fast serialization alternative to JSON.stringify.

Gracefully handles circular structures instead of throwing in most cases. It could return an error string if the circular object is too complex to analyze, e.g. in case there are proxies involved.

Provides a deterministic ("stable") version as well that will also gracefully handle circular structures. See the example below for further information.

Usage

The same as JSON.stringify.

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

const safeStringify = require('fast-safe-stringify')
const o = { a: 1 }
o.o = o

console.log(safeStringify(o))
// '{"a":1,"o":"[Circular]"}'
console.log(JSON.stringify(o))
// TypeError: Converting circular structure to JSON

function replacer(key, value) {
  console.log('Key:', JSON.stringify(key), 'Value:', JSON.stringify(value))
  // Remove the circular structure
  if (value === '[Circular]') {
    return
  }
  return value
}

// those are also defaults limits when no options object is passed into safeStringify
// configure it to lower the limit.
const options = {
  depthLimit: Number.MAX_SAFE_INTEGER,
  edgesLimit: Number.MAX_SAFE_INTEGER
};

const serialized = safeStringify(o, replacer, 2, options)
// Key: "" Value: {"a":1,"o":"[Circular]"}
// Key: "a" Value: 1
// Key: "o" Value: "[Circular]"
console.log(serialized)
// {
//  "a": 1
// }

Using the deterministic version also works the same:

const safeStringify = require('fast-safe-stringify')
const o = { b: 1, a: 0 }
o.o = o

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

A faster and side-effect free implementation is available in the [safe-stable-stringify][] module. However it is still considered experimental due to a new and more complex implementation.

Replace strings constants

  • [Circular] - when same reference is found
  • [...] - when some limit from options object is reached

Differences to JSON.stringify

In general the behavior is identical to JSON.stringify. The replacer and space options are also available.

A few exceptions exist to JSON.stringify while using toJSON or replacer:

Regular safe stringify

  • Manipulating a circular structure of the passed in value in a toJSON or the replacer is not possible! It is possible for any other value and property.

  • In case a circular structure is detected and the replacer is used it will receive the string [Circular] as the argument instead of the circular object itself.

Deterministic ("stable") safe stringify

  • Manipulating the input object either in a toJSON or the replacer function will not have any effect on the output. The output entirely relies on the shape the input value had at the point passed to the stringify function!

  • In case a circular structure is detected and the replacer is used it will receive the string [Circular] as the argument instead of the circular object itself.

A side effect free variation without these limitations can be found as well (safe-stable-stringify). It is also faster than the current implementation. It is still considered experimental due to a new and more complex implementation.

Benchmarks

Although not JSON, the Node.js util.inspect method can be used for similar purposes (e.g. logging) and also handles circular references.

Here we compare fast-safe-stringify with some alternatives: (Lenovo T450s with a i7-5600U CPU using Node.js 8.9.4)

fast-safe-stringify:   simple object x 1,121,497 ops/sec ±0.75% (97 runs sampled)
fast-safe-stringify:   circular      x 560,126 ops/sec ±0.64% (96 runs sampled)
fast-safe-stringify:   deep          x 32,472 ops/sec ±0.57% (95 runs sampled)
fast-safe-stringify:   deep circular x 32,513 ops/sec ±0.80% (92 runs sampled)

util.inspect:          simple object x 272,837 ops/sec ±1.48% (90 runs sampled)
util.inspect:          circular      x 116,896 ops/sec ±1.19% (95 runs sampled)
util.inspect:          deep          x 19,382 ops/sec ±0.66% (92 runs sampled)
util.inspect:          deep circular x 18,717 ops/sec ±0.63% (96 runs sampled)

json-stringify-safe:   simple object x 233,621 ops/sec ±0.97% (94 runs sampled)
json-stringify-safe:   circular      x 110,409 ops/sec ±1.85% (95 runs sampled)
json-stringify-safe:   deep          x 8,705 ops/sec ±0.87% (96 runs sampled)
json-stringify-safe:   deep circular x 8,336 ops/sec ±2.20% (93 runs sampled)

For stable stringify comparisons, see the performance benchmarks in the safe-stable-stringify readme.

Protip

Whether fast-safe-stringify or alternatives are used: if the use case consists of deeply nested objects without circular references the following pattern will give best results. Shallow or one level nested objects on the other hand will slow down with it. It is entirely dependant on the use case.

const stringify = require('fast-safe-stringify')

function tryJSONStringify (obj) {
  try { return JSON.stringify(obj) } catch (_) {}
}

const serializedString = tryJSONStringify(deep) || stringify(deep)

Acknowledgements

Sponsored by nearForm

License

MIT