Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
circular-json
Advanced tools
The circular-json npm package is designed to handle JSON serialization and deserialization of objects that contain circular references. This is particularly useful when working with complex data structures that would otherwise cause errors with the standard JSON.stringify and JSON.parse methods.
Stringify with Circular References
This feature allows you to convert an object with circular references into a JSON string without causing errors. The code sample demonstrates how to stringify an object that references itself.
const CircularJSON = require('circular-json');
const obj = {};
obj.self = obj;
const jsonString = CircularJSON.stringify(obj);
console.log(jsonString);
Parse with Circular References
This feature allows you to parse a JSON string that contains circular references back into an object. The code sample shows how to parse a JSON string that represents an object with a circular reference.
const CircularJSON = require('circular-json');
const jsonString = '{"self":"~"}';
const obj = CircularJSON.parse(jsonString);
console.log(obj);
Flatted is a similar package that provides a way to serialize and deserialize objects with circular references. It uses a different approach by creating a special JSON format that can be parsed back into the original object. Compared to circular-json, flatted is more modern and actively maintained.
json-stringify-safe is another package that handles circular references during JSON serialization. It provides a drop-in replacement for JSON.stringify that doesn't throw errors on circular references. Unlike circular-json, it does not provide a custom parse method.
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:
JSON.stringify
and JSON.parse
methods with same type of arguments (same JSON API, an extra optional argument has been added to .stringify()
to support simple placeholder)CircularJSON.stringify(data, null, null, true)
can produce an output with "[Circular]"
placeholder as other implementations might do.A proper JSON object must be globally available if the browser/engine does not support it.
Dependencies free if you target IE8 and greater or any server side JS engine.
Bear in mind JSON.parse(CircularJSON.stringify(object))
will work but not produce the expected output.
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))
.
The usual structure for my repos, the one generated via gitstrap, so:
npm install circular-json
and later on var CircularJSON = require('circular-json')
The API is the same as JSON Object so nothing new to learn here while full test coverage is also in the usual place with some example included.
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.
FAQs
JSON does not handle circular references. This version does
The npm package circular-json receives a total of 1,074,038 weekly downloads. As such, circular-json popularity was classified as popular.
We found that circular-json demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.