Skip to content

Instantly share code, notes, and snippets.

@emersondemetrio
Created September 16, 2022 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emersondemetrio/5943ff1ef212c152f26a45d0ed933574 to your computer and use it in GitHub Desktop.
Save emersondemetrio/5943ff1ef212c152f26a45d0ed933574 to your computer and use it in GitHub Desktop.
Circular Safe Json Stringfy
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