Menu

gitpiper

stringifyCircularJSON javascript Code Snippet in 2024

objectadvanced

Last Updated: 28 December 2024

Serializes a JSON object containing circular references into a JSON format.

  • Create a new WeakSet() to store and check seen values, using WeakSet.prototype.add() and WeakSet.prototype.has().
  • Use JSON.stringify() with a custom replacer function that omits values already in seen, adding new values as necessary.
  • ⚠️ NOTICE: This function finds and removes circular references, which causes circular data loss in the serialized JSON.
const stringifyCircularJSON = obj => { const seen = new WeakSet(); return JSON.stringify(obj, (k, v) => { if (v !== null && typeof v === 'object') { if (seen.has(v)) return; seen.add(v); } return v; }); };
const obj = { n: 42 }; obj.obj = obj; stringifyCircularJSON(obj); // '{"n": 42}'

javascript snippet similar to stringifyCircularJSON For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️