BKJang / dev-tips

📚 This repository is a collection of development tips and troubleshooting I have experienced during development.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JSON.stringify circular structure

BKJang opened this issue · comments

❓ What is the cause of this issue?

JSON.stringify()는 순환참조를 발견하면 TypeError를 발생시킨다.

var obj = { a: 1 };
obj.child = obj;
console.log( JSON.stringify( obj ) ); // TypeError: Converting circular structure to JSON

🔨 What have I tried? How did you finally solve it?

var cache = [];
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; // Enable garbage collection

👍 Is there any better way?

const getCircularReplacer = () => {
  const seen = new WeakSet();
  return (key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) {
        return;
      }
      seen.add(value);
    }
    return value;
  };
};

JSON.stringify(obj, getCircularReplacer());

🙏 Reference