Created
February 8, 2022 03:57
-
-
Save RexSkz/c4f78a6e143e9008f9c717623b7a2bc1 to your computer and use it in GitHub Desktop.
JSON.stringify with depth limit
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
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); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Respect the original
JSON.stringify
params (which means it can safely replaceJSON.stringify
), written in TypeScript.