circular-json vs flatted vs json-stringify-safe
Handling Circular References in JavaScript Serialization
circular-jsonflattedjson-stringify-safeSimilar 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
circular-json0610-07 years agoMIT
flatted01,12038.4 kB12 days agoISC
json-stringify-safe0554-711 years agoISC

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: circular-json vs flatted vs json-stringify-safe

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

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

README for circular-json

CircularJSON

donate Downloads Build Status Coverage Status

Serializes and deserializes otherwise valid JSON objects containing circular references into and from a specialized JSON format.


The future of this module is called flatted

Smaller, faster, and able to produce on average a reduced output too, flatted is the new, bloatless, ESM and CJS compatible, circular JSON parser.

It has now reached V1 and it implements the exact same JSON API.

Please note CircularJSON is in maintenance only and flatted is its successor.


A Working Solution To A Common Problem

A usage example:

var object = {};
object.arr = [
  object, object
];
object.arr.push(object.arr);
object.obj = object;

var serialized = CircularJSON.stringify(object);
// '{"arr":["~","~","~arr"],"obj":"~"}'
// NOTE: CircularJSON DOES NOT parse JS
// it handles receiver and reviver callbacks

var unserialized = CircularJSON.parse(serialized);
// { arr: [ [Circular], [Circular] ],
// obj: [Circular] }

unserialized.obj === unserialized;
unserialized.arr[0] === unserialized;
unserialized.arr.pop() === unserialized.arr;

A quick summary:

  • new in version 0.5, you can specify a JSON parser different from JSON itself. CircularJSON.parser = ABetterJSON; is all you need.
  • uses ~ as a special prefix symbol to denote which parent the reference belongs to (i.e. ~root~child1~child2)
  • reasonably fast in both serialization and deserialization
  • compact serialization for easier and slimmer transportation across environments
  • tested and covered over nasty structures too
  • compatible with all JavaScript engines

Node Installation & Usage

npm install --save circular-json
'use strict';

var
  CircularJSON = require('circular-json'),
  obj = { foo: 'bar' },
  str
;
  
obj.self = obj;
str = CircularJSON.stringify(obj);

There are no dependencies.

Browser Installation & Usage

  • Global: <build/circular-json.js>
  • AMD: <build/circular-json.amd.js>
  • CommonJS: <build/circular-json.node.js>

(generated via gitstrap)

<script src="build/circular-json.js"></script>
'use strict';

var CircularJSON = window.CircularJSON
  , obj = { foo: 'bar' }
  , str
  ;
  
obj.self = obj;
str = CircularJSON.stringify(obj);

NOTE: Platforms without native JSON (i.e. MSIE <= 8) requires json3.js or similar.

It is also a bad idea to CircularJSON.parse(JSON.stringify(object)) because of those manipulation used in CircularJSON.stringify() able to make parsing safe and secure.

As summary: CircularJSON.parse(CircularJSON.stringify(object)) is the way to go, same is for JSON.parse(JSON.stringify(object)).

API

It's the same as native JSON, except the fourth parameter placeholder, which circular references to be replaced with "[Circular]" (i.e. for logging).

  • CircularJSON.stringify(object, replacer, spacer, placeholder)
  • CircularJSON.parse(string, reviver)

Bear in mind JSON.parse(CircularJSON.stringify(object)) will work but not produce the expected output.

Similar Libraries

Why Not the @izs One

The module json-stringify-safe seems to be for console.log() but it's completely pointless for JSON.parse(), being latter one unable to retrieve back the initial structure. Here an example:

// a logged object with circular references
{
  "circularRef": "[Circular]",
  "list": [
    "[Circular]",
    "[Circular]"
  ]
}
// what do we do with above output ?

Just type this in your node console: var o = {}; o.a = o; console.log(o);. The output will be { a: [Circular] } ... good, but that ain't really solving the problem.

However, if that's all you need, the function used to create that kind of output is probably faster than CircularJSON and surely fits in less lines of code.

Why Not {{put random name}} Solution

So here the thing: circular references can be wrong but, if there is a need for them, any attempt to ignore them or remove them can be considered just a failure.

Not because the method is bad or it's not working, simply because the circular info, the one we needed and used in the first place, is lost!

In this case, CircularJSON does even more than just solve circular and recursions: it maps all same objects so that less memory is used as well on deserialization as less bandwidth too! It's able to redefine those references back later on so the way we store is the way we retrieve and in a reasonably performant way, also trusting the snappy and native JSON methods to iterate.