Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function prettyJson(object, indent = 4, stack = []) {
- stack.push(object);
- let result = "{\n";
- let indentString = (new Array(indent+1)).join(" ");
- let indentEnd = (new Array(indent-3)).join(" ");
- let keys = Object.keys(object);
- keys.forEach((key, i) => {
- let value = object[key];
- result += indentString + `"${key}": `;
- if(typeof value === "object") result += stack.includes(value) ? "[Circular Object]" : prettyJson(value, indent + 4, stack);
- else if(typeof value === "string") result += `"${value}"`;
- else result += value;
- result += i === (keys.length - 1) ? "\n" : ",\n";
- });
- return result + indentEnd + "}"
- }
- // use as prettyJson({ a: 1, b: 2, c: '3', nested: { d: false, e: 4, j: 'string' } })
Add Comment
Please, Sign In to add comment