Sometimes you want to display a Javascript object as a string and when you use JSON.stringify you get an error: Converting circular structure to JSON. The solution is to use a function that keeps a record of objects found and returns a text explaining where the circular reference appeared. Here is a simple function like that:
function fixCircularReferences() {
const defs={};
return (k,v) => {
const def = defs[v];
if (def && typeof(v) == 'object') return '['+k+' is the same as '+def+']';
defs[v]=k;
return v;
}
}

And the usage is
JSON.stringify(someObject,fixCircularReferences(),2);
. If you want to use it as a JSON (so serialize the object for real), replace the return of a string with
return null
, although that means you have not properly serialized the initial object.

The function is something I cropped up in a minute or so. If there are some edge cases where it didn't work, let me know and I will update it.

Comments

Siderite

As far as I know an object reference is what is used as the "key" in the internal dictionary. It's never transformed to a string.

Siderite

???

this seems to use objects themselves as keys for def, which will not work for objects that do not return a unique string from toJSON...

???

John C

Lifesaver!! When using in (for example) Chrome's DevTools, usage is as simple as: > fx = function fixCircularReferences() { ...} <- undefined > JSON.stringify(object, fx(), 2) <- '{...}'

John C

Post a comment