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.
Created
May 14, 2025 13:07
-
-
Save ali-master/57bb7083afecb4007a822f8ac1d282b1 to your computer and use it in GitHub Desktop.
Converting circular structure to JSON in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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