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.
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.
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.
Serializes and deserializes otherwise valid JSON objects containing circular references into and from a specialized JSON format.
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 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:
0.5, you can specify a JSON parser different from JSON itself. CircularJSON.parser = ABetterJSON; is all you need.~ as a special prefix symbol to denote which parent the reference belongs to (i.e. ~root~child1~child2)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.
(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)).
It's the same as native JSON, except the fourth parameter placeholder, which circular references to be replaced with "[Circular]" (i.e. for logging).
Bear in mind JSON.parse(CircularJSON.stringify(object)) will work but not produce the expected output.
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.
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.