Update and rename circularJSONStringify.md to stringifyCircularJSON.md

This commit is contained in:
Angelos Chalaris
2020-10-06 12:32:28 +03:00
committed by GitHub
parent a1363905e8
commit cba8422274
2 changed files with 29 additions and 30 deletions

View File

@ -1,30 +0,0 @@
---
title: circularJSONStringify
tags: object,intermediate
---
Serializes valid JSON objects containing circular references into a JSON format.
- Use `JSON.stringify` with a custom replacer
- ⚠️ **NOTICE:** This function finds and removes circular references, what causes data loss
```js
const circularJSONStringify = object => {
const cache = new WeakSet();
return JSON.stringify(object, (key, value) => {
if (value !== null && typeof value === 'object') {
if (cache.has(value)) return;
cache.add(value);
}
return value;
});
};
```
```js
const obj = { n: 42 };
obj.obj = obj;
circularJSONStringify(obj); // '{"n": 42}'
```

View File

@ -0,0 +1,29 @@
---
title: stringifyCircularJSON
tags: object,advanced
---
Serializes a JSON object containing circular references into a JSON format.
- Create a `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.
```js
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;
});
};
```
```js
const obj = { n: 42 };
obj.obj = obj;
stringifyCircularJSON(obj); // '{"n": 42}'
```