Friday, June 15, 2018

JSON.stringify with circular references and nicely indented

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+']';
    return v;

And the usage is
. 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.