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.
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.
circular-json: Encode → Stringify → Decodecircular-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-jsonis deprecated. The author explicitly recommends usingflattedinstead. Do not use this in new projects.
flatted: Leverage JSON’s Native Structure with Path-Based Referencesflatted 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 ValuesUnlike 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.
circular-json: ✅ Yes — via CircularJSON.parse()flatted: ✅ Yes — via flatted.parse()json-stringify-safe: ❌ No — it’s a lossy, one-way operationIf 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.
All three handle basic cycles, but differ on edge cases:
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.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]".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.flatted when:// Saving and restoring state with flatted
localStorage.setItem('state', stringify(reduxState));
const restoredState = parse(localStorage.getItem('state'));
json-stringify-safe when:// Safe logging
console.log(stringify(errorContext)); // Won't crash, even with cycles
circular-json:flatted as its successor.| Feature | circular-json | flatted | json-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 case | Legacy projects only | Full round-trip serialization | Debugging / logging |
flatted. It’s lightweight, well-designed, and actively maintained.json-stringify-safe. It’s battle-tested and perfect for observability.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.
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.
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.
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.

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.
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"}]
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
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.
.parse(string, reviver) and revive your own objects.space parameter to .stringify(object, replacer, space) for feature parity with JSON signature.All ECMAScript engines compatible with Map, Set, Object.keys, and Array.prototype.reduce will work, even if polyfilled.
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'