Guest User

Untitled

a guest
Mar 17th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. function prettyJson(object, indent = 4, stack = []) {
  2. stack.push(object);
  3.  
  4. let result = "{\n";
  5.  
  6. let indentString = (new Array(indent+1)).join(" ");
  7. let indentEnd = (new Array(indent-3)).join(" ");
  8.  
  9. let keys = Object.keys(object);
  10. keys.forEach((key, i) => {
  11. let value = object[key];
  12.  
  13. result += indentString + `"${key}": `;
  14. if(typeof value === "object") result += stack.includes(value) ? "[Circular Object]" : prettyJson(value, indent + 4, stack);
  15. else if(typeof value === "string") result += `"${value}"`;
  16. else result += value;
  17.  
  18. result += i === (keys.length - 1) ? "\n" : ",\n";
  19. });
  20.  
  21. return result + indentEnd + "}"
  22. }
  23.  
  24. // use as prettyJson({ a: 1, b: 2, c: '3', nested: { d: false, e: 4, j: 'string' } })
Add Comment
Please, Sign In to add comment