942 B
942 B
title, type, language, tags, cover, dateModified
| title | type | language | tags | cover | dateModified | |
|---|---|---|---|---|---|---|
| Stringify circular JSON | snippet | javascript |
|
waving-over-lake | 2020-10-22T20:24:30+03:00 |
Serializes a JSON object containing circular references into a JSON format.
- Create a
WeakSetto store and check seen values, usingWeakSet.prototype.add()andWeakSet.prototype.has(). - Use
JSON.stringify()with a custom replacer function that omits values already inseen, 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}'