Which is Better JSON Serialization Libraries?
flatted vs json-stringify-safe vs circular-json
1 Year
flattedjson-stringify-safecircular-jsonSimilar Packages:
What's JSON Serialization Libraries?

JSON serialization libraries are essential tools in web development that allow developers to convert JavaScript objects into JSON format and vice versa. These libraries address the limitations of the native JSON methods, particularly when dealing with complex data structures such as circular references, which can lead to errors during serialization. Each of these libraries provides unique features to handle specific serialization challenges, making them valuable for various use cases in data handling and storage.

NPM Package Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
flatted38,835,5551,03340.3 kB28 months agoISC
json-stringify-safe23,092,193550-79 years agoISC
circular-json1,160,547605-06 years agoMIT
Feature Comparison: flatted vs json-stringify-safe vs circular-json

Circular Reference Handling

  • flatted: Flatted efficiently handles circular references by using a unique identifier for each object, allowing for the reconstruction of the original object structure during deserialization. This method is both memory-efficient and fast, making it suitable for performance-critical applications.
  • json-stringify-safe: json-stringify-safe prevents errors caused by circular references by replacing them with a string '[Circular]' during serialization. This approach allows for safe logging and debugging without crashing the application, although it may not fully reconstruct the original object structure.
  • circular-json: Circular JSON provides a simple way to serialize objects that contain circular references by replacing circular references with a placeholder. This allows for the serialization of complex object graphs without throwing errors, making it ideal for applications that frequently deal with such structures.

Performance

  • flatted: Flatted is designed for speed and efficiency, making it one of the fastest options for handling circular references. Its lightweight implementation ensures minimal overhead, which is beneficial for applications that require high performance during serialization and deserialization processes.
  • json-stringify-safe: json-stringify-safe offers reasonable performance for most use cases, but it may not be as fast as Flatted. Its focus is on safety and compatibility rather than raw speed, making it suitable for applications where stability is more critical than performance.
  • circular-json: Circular JSON is relatively fast for serialization and deserialization, but its performance may degrade with highly nested or complex objects due to the overhead of managing circular references. It is generally suitable for most applications but may not be the best choice for performance-critical scenarios.

API Simplicity

  • flatted: Flatted provides a clean and modern API that is easy to use, making it accessible for developers of all skill levels. Its design encourages straightforward integration into existing projects, allowing for quick adoption without significant changes to the codebase.
  • json-stringify-safe: json-stringify-safe offers a familiar API for developers already accustomed to JSON serialization. Its method names and usage patterns are similar to native JSON methods, facilitating a smooth transition for developers looking to enhance their serialization capabilities.
  • circular-json: Circular JSON has a straightforward API that closely resembles the native JSON methods, making it easy to integrate into existing codebases. This simplicity allows developers to adopt it quickly without a steep learning curve, which is beneficial for rapid development cycles.

Use Cases

  • flatted: Flatted is ideal for modern web applications that require efficient serialization of complex data structures, especially in performance-sensitive environments like real-time applications or large-scale data processing tasks. Its lightweight nature makes it a strong candidate for these use cases.
  • json-stringify-safe: json-stringify-safe is particularly useful for logging and debugging applications where complex objects need to be serialized without causing crashes. It is also suitable for scenarios where data integrity is essential, and developers want to avoid losing information during serialization.
  • circular-json: Circular JSON is best suited for applications that frequently handle complex object graphs, such as data models in web applications or APIs that return nested structures. Its ability to serialize circular references makes it a go-to choice for such scenarios.

Community and Maintenance

  • flatted: Flatted is a newer library with a growing community, and its active maintenance ensures that it adapts to modern JavaScript standards. Its focus on performance and efficiency is likely to attract more users, contributing to its ongoing development.
  • json-stringify-safe: json-stringify-safe has been around for a while and has a solid user base. Its maintenance is consistent, and it is widely used in various applications, providing a level of trust and reliability for developers.
  • circular-json: Circular JSON has a stable community and is maintained actively, ensuring that it stays up-to-date with the latest JavaScript features and best practices. This level of maintenance provides confidence for developers looking for reliable libraries.
How to Choose: flatted vs json-stringify-safe vs circular-json
  • flatted: Opt for Flatted if you want a modern and efficient solution for serializing and deserializing objects with circular references. Flatted is designed to be lightweight and fast, making it suitable for performance-sensitive applications. It also has a simple API that can be easily integrated into existing codebases.
  • json-stringify-safe: Select json-stringify-safe if you need a robust solution that prevents errors during serialization of objects with circular references while maintaining compatibility with standard JSON serialization. It is particularly useful for logging and debugging scenarios where you want to serialize complex objects without crashing the application.
  • circular-json: Choose Circular JSON if you need to serialize and deserialize objects with circular references easily. It is straightforward to use and integrates seamlessly with existing JSON methods, making it a good choice for projects that require handling complex object graphs.
README for flatted

flatted

Downloads Coverage Status Build Status License: ISC WebReflection status

snow flake

Social Media Photo by Matt Seymour on Unsplash

A super light (0.5K) and fast circular JSON parser, directly from the creator of CircularJSON.

Available also for PHP.

Available also for Python.


Announcement 📣

There is a standard approach to recursion and more data-types than what JSON allows, and it's part of the Structured Clone polyfill.

Beside acting as a polyfill, its @ungap/structured-clone/json export provides both stringify and parse, and it's been tested for being faster than flatted, but its produced output is also smaller than flatted in general.

The @ungap/structured-clone module is, in short, a drop in replacement for flatted, but it's not compatible with flatted specialized syntax.

However, if recursion, as well as more data-types, are what you are after, or interesting for your projects/use cases, consider switching to this new module whenever you can 👍


npm i flatted

Usable via CDN or as regular module.

// ESM
import {parse, stringify, toJSON, fromJSON} from 'flatted';

// CJS
const {parse, stringify, toJSON, fromJSON} = require('flatted');

const a = [{}];
a[0].a = a;
a.push(a);

stringify(a); // [["1","0"],{"a":"0"}]

toJSON and fromJSON

If you'd like to implicitly survive JSON serialization, these two helpers helps:

import {toJSON, fromJSON} from 'flatted';

class RecursiveMap extends Map {
  static fromJSON(any) {
    return new this(fromJSON(any));
  }
  toJSON() {
    return toJSON([...this.entries()]);
  }
}

const recursive = new RecursiveMap;
const same = {};
same.same = same;
recursive.set('same', same);

const asString = JSON.stringify(recursive);
const asMap = RecursiveMap.fromJSON(JSON.parse(asString));
asMap.get('same') === asMap.get('same').same;
// true

Flatted VS JSON

As it is for every other specialized format capable of serializing and deserializing circular data, you should never JSON.parse(Flatted.stringify(data)), and you should never Flatted.parse(JSON.stringify(data)).

The only way this could work is to Flatted.parse(Flatted.stringify(data)), as it is also for CircularJSON or any other, otherwise there's no granted data integrity.

Also please note this project serializes and deserializes only data compatible with JSON, so that sockets, or anything else with internal classes different from those allowed by JSON standard, won't be serialized and unserialized as expected.

New in V1: Exact same JSON API

  • Added a reviver parameter to .parse(string, reviver) and revive your own objects.
  • Added a replacer and a space parameter to .stringify(object, replacer, space) for feature parity with JSON signature.

Compatibility

All ECMAScript engines compatible with Map, Set, Object.keys, and Array.prototype.reduce will work, even if polyfilled.

How does it work ?

While stringifying, all Objects, including Arrays, and strings, are flattened out and replaced as unique index. *

Once parsed, all indexes will be replaced through the flattened collection.

* represented as string to avoid conflicts with numbers

// logic example
var a = [{one: 1}, {two: '2'}];
a[0].a = a;
// a is the main object, will be at index '0'
// {one: 1} is the second object, index '1'
// {two: '2'} the third, in '2', and it has a string
// which will be found at index '3'

Flatted.stringify(a);
// [["1","2"],{"one":1,"a":"0"},{"two":"3"},"2"]
// a[one,two]    {one: 1, a}    {two: '2'}  '2'