Skip to content

Instantly share code, notes, and snippets.

@RexSkz
Created February 8, 2022 03:57
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 RexSkz/c4f78a6e143e9008f9c717623b7a2bc1 to your computer and use it in GitHub Desktop.
Save RexSkz/c4f78a6e143e9008f9c717623b7a2bc1 to your computer and use it in GitHub Desktop.
JSON.stringify with depth limit
const stringify = (
obj: any,
replacer?: (this: any, key: string, value: any) => any,
space?: string | number,
depth = Infinity,
): string => {
if (!obj || typeof obj !== 'object') {
return JSON.stringify(obj, replacer, space);
}
const t = depth < 1
? '"..."'
: Array.isArray(obj)
? `[${obj.map(v => stringify(v, replacer, space, depth - 1)).join(',')}]`
: `{${Object.keys(obj)
.map((k) => `"${k}": ${stringify(obj[k], replacer, space, depth - 1)}`)
.join(', ')}}`;
return JSON.stringify(JSON.parse(t), replacer, space);
};
@RexSkz
Copy link
Author

RexSkz commented Feb 8, 2022

Respect the original JSON.stringify params (which means it can safely replace JSON.stringify), written in TypeScript.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment