Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created May 14, 2025 13:07
Show Gist options
  • Save ali-master/57bb7083afecb4007a822f8ac1d282b1 to your computer and use it in GitHub Desktop.
Save ali-master/57bb7083afecb4007a822f8ac1d282b1 to your computer and use it in GitHub Desktop.
Converting circular structure to JSON in JS

When does this error occur?

This error occurs when you try to convert a JavaScript object to JSON, but the object contains a circular reference. A circular reference occurs when an object refers to itself, directly or indirectly.

function stringify(obj) {
let cache = [];
let str = JSON.stringify(obj, function(key, value) {
if (typeof value === "object" && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
cache = null; // reset the cache
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment