Created
September 16, 2022 15:55
-
-
Save emersondemetrio/5943ff1ef212c152f26a45d0ed933574 to your computer and use it in GitHub Desktop.
Circular Safe Json Stringfy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type JsonLike = { | |
[key: string]: string | number | undefined | null | JsonLike; | |
}; | |
const getCircularReplacer = () => { | |
const seen = new WeakSet(); | |
return (_, value: JsonLike) => { | |
if (typeof value === 'object' && value !== null) { | |
if (seen.has(value)) { | |
return; | |
} | |
seen.add(value); | |
} | |
return value; | |
}; | |
}; | |
const safeStringify = (data: JsonLike) => | |
JSON.stringify(data, getCircularReplacer()); | |
const example: JsonLike = { | |
data1: 1, | |
}; | |
example.data2 = example; | |
console.log('Original JSON', example); | |
/** | |
* { | |
* data1: 1, | |
* data2: { data1: 1, data2: ... } | |
* } | |
*/ | |
console.log(safeStringify(example)); | |
/** | |
* { | |
* "data1": 1 | |
* } | |
*/ | |
// Credits: | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#examples |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment