Skip to content

Instantly share code, notes, and snippets.

@RexSkz
Created February 8, 2022 03:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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