flatted vs json-stringify-safe vs circular-json
Handling Circular References in JavaScript Serialization
flattedjson-stringify-safecircular-jsonSimilar Packages:
Handling Circular References in JavaScript Serialization

circular-json, flatted, and json-stringify-safe are npm packages designed to handle the limitations of JavaScript's native JSON.stringify() when dealing with circular references or non-serializable values. circular-json (now deprecated) and flatted provide reversible serialization by encoding circular structures into valid JSON and offering a corresponding parse method to restore the original object graph. In contrast, json-stringify-safe offers a one-way, lossy stringification that replaces problematic values (like circular references or functions) with placeholder strings, making it suitable for logging or debugging but not for data reconstruction.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
flatted69,140,4601,10831.5 kB0a year agoISC
json-stringify-safe27,317,676554-711 years agoISC
circular-json1,217,007608-07 years agoMIT

Handling Circular References in JavaScript: circular-json vs flatted vs json-stringify-safe

When working with complex JavaScript objects — especially those involving DOM nodes, class instances, or bidirectional relationships — you’ll eventually hit a wall with JSON.stringify(). It throws a TypeError: Converting circular structure to JSON the moment it detects a loop. The three packages under review (circular-json, flatted, and json-stringify-safe) each offer a way around this problem, but they do so with very different strategies, trade-offs, and maintenance statuses. Let’s break down what each actually does, how they work, and which one deserves your attention in 2024.

🔄 Core Strategy: How Each Package Handles Cycles

circular-json: Encode → Stringify → Decode

circular-json uses a two-step process: first, it walks the object tree and replaces circular references with special placeholder strings (like "$ref$0"). Then it safely calls JSON.stringify() on the transformed structure. To restore the original object, you use CircularJSON.parse(), which reverses the transformation.

// circular-json example
import CircularJSON from 'circular-json';

const obj = { a: 1 };
obj.self = obj; // circular reference

const serialized = CircularJSON.stringify(obj);
// Result: '{"a":1,"self":"$ref$0"}'

const restored = CircularJSON.parse(serialized);
console.log(restored.self === restored); // true

⚠️ Important: According to its npm page, circular-json is deprecated. The author explicitly recommends using flatted instead. Do not use this in new projects.

flatted: Leverage JSON’s Native Structure with Path-Based References

flatted takes a clever approach by converting any object into an array where the first element is the root object, and subsequent elements represent referenced sub-objects. It uses string keys like "1" or "2" to point to indices in that array. This avoids inventing custom syntax and stays within standard JSON.

// flatted example
import { stringify, parse } from 'flatted';

const obj = { a: 1 };
obj.self = obj;

const serialized = stringify(obj);
// Result: '[{"a":1,"self":"1"},"0"]'
// Explanation: Root object at index 0, "self" points to index 1, which is "0" (a string pointing back to index 0)

const restored = parse(serialized);
console.log(restored.self === restored); // true

This method is fully compatible with native JSON.parse() for the outer structure — only the inner logic of reconstruction requires flatted.parse().

json-stringify-safe: Silently Drop or Replace Problematic Values

Unlike the other two, json-stringify-safe doesn’t preserve circular structures. Instead, it avoids errors by replacing circular references (and other non-serializable values like functions) with a placeholder — by default, the string "[Circular]". There’s no built-in way to reconstruct the original object.

// json-stringify-safe example
import stringify from 'json-stringify-safe';

const obj = { a: 1 };
obj.self = obj;
obj.fn = () => {};

const serialized = stringify(obj);
// Result: '{"a":1,"self":"[Circular]","fn":"[Function]"}'

// No parse() method — this is one-way serialization only

This is useful for logging or debugging, where you just need a readable snapshot — not a reversible transformation.

🔁 Reversibility: Can You Get Your Object Back?

  • circular-json: ✅ Yes — via CircularJSON.parse()
  • flatted: ✅ Yes — via flatted.parse()
  • json-stringify-safe: ❌ No — it’s a lossy, one-way operation

If your goal is to transmit or store a complex object and later reconstruct it exactly, only circular-json and flatted qualify. But since circular-json is deprecated, flatted becomes the only viable reversible option.

🧪 Behavior with Edge Cases

All three handle basic cycles, but differ on edge cases:

Multiple references to the same object

const shared = { value: 42 };
const obj = { a: shared, b: shared };
  • flatted preserves referential identity: after parse(), obj.a === obj.b is true.
  • circular-json also preserves identity (but again — deprecated).
  • json-stringify-safe turns both into {"value":42} as plain objects — so obj.a === obj.b becomes false.

Non-object values (functions, undefined, symbols)

  • flatted and circular-json will throw or behave unpredictably with functions/symbols — they assume you’re working with plain objects.
  • json-stringify-safe explicitly handles them by replacing with descriptive strings like "[Function]" or "[undefined]".

🛠️ API Design and Integration

  • flatted exports stringify and parse — clean, minimal, and mirrors the native JSON API.
  • circular-json uses static methods (CircularJSON.stringify / .parse) — slightly more verbose.
  • json-stringify-safe only provides a stringify function — no parsing capability.

📦 Real-World Use Cases

Use flatted when:

  • You need to serialize and later reconstruct complex objects with cycles (e.g., saving app state, sending data over WebSockets).
  • You want a maintained, modern solution that works reliably with nested references.
  • Example: Storing a Redux state tree that includes entity relationships with back-references.
// Saving and restoring state with flatted
localStorage.setItem('state', stringify(reduxState));
const restoredState = parse(localStorage.getItem('state'));

Use json-stringify-safe when:

  • You’re logging objects for debugging or error reporting.
  • You don’t care about reconstruction — just want to avoid crashes during serialization.
  • Example: Sending error context to a logging service like Sentry.
// Safe logging
console.log(stringify(errorContext)); // Won't crash, even with cycles

Avoid circular-json:

  • It’s officially deprecated.
  • The author (Andrea Giammarchi) now maintains flatted as its successor.
  • Using it introduces technical debt and potential security risks from unmaintained code.

🆚 Summary Table

Featurecircular-jsonflattedjson-stringify-safe
Reversible?✅ Yes✅ Yes❌ No
Preserves references?✅ Yes✅ Yes❌ No (creates copies)
Handles functions?❌ No❌ No✅ Replaces with string
Maintenance status⚠️ Deprecated✅ Actively maintained✅ Maintained
Use caseLegacy projects onlyFull round-trip serializationDebugging / logging

💡 Final Recommendation

  • For new projects requiring reversible serialization: Use flatted. It’s lightweight, well-designed, and actively maintained.
  • For logging or one-way safe stringification: Use json-stringify-safe. It’s battle-tested and perfect for observability.
  • Do not use circular-json — it’s deprecated, and flatted is its direct, improved replacement.

In short: if you need to save and restore complex state, go with flatted. If you just need to print without crashing, json-stringify-safe has your back.

How to Choose: flatted vs json-stringify-safe vs circular-json
  • flatted:

    Choose flatted when you need to serialize complex objects with circular references or shared sub-objects and later reconstruct them exactly as they were. It uses a clever, standards-compliant encoding strategy that preserves referential identity and works reliably across environments. It’s actively maintained, lightweight, and ideal for use cases like saving application state, transmitting object graphs over networks, or caching structured data that must be restored faithfully.

  • json-stringify-safe:

    Choose json-stringify-safe when your goal is safe, one-way serialization for logging, debugging, or error reporting — not data reconstruction. It gracefully replaces circular references, functions, and other non-serializable values with descriptive placeholder strings (e.g., "[Circular]"), preventing crashes during JSON.stringify(). Since it doesn’t support parsing or object restoration, it’s unsuitable for data persistence but excellent for observability pipelines.

  • circular-json:

    Do not use circular-json in new projects — it is officially deprecated according to its npm page, and the author recommends migrating to flatted. While it once provided reversible serialization of circular structures, it is no longer maintained and introduces unnecessary risk. If you encounter it in legacy code, plan to replace it with flatted during refactoring.

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'