Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON.stringify circular structure #36

Open
BKJang opened this issue Oct 29, 2019 · 0 comments
Open

JSON.stringify circular structure #36

BKJang opened this issue Oct 29, 2019 · 0 comments
Labels
completed This is completed. Javascript This is related to Javascript. Tip This is tip for developement.

Comments

@BKJang
Copy link
Owner

BKJang commented Oct 29, 2019

❓ 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

@BKJang BKJang added completed This is completed. Javascript This is related to Javascript. Tip This is tip for developement. labels Oct 29, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
completed This is completed. Javascript This is related to Javascript. Tip This is tip for developement.
Projects
None yet
Development

No branches or pull requests

1 participant