Guest User

Untitled

a guest
Aug 17th, 2019
68
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function beautifyJSON(input) {
  2. var formatted = '';
  3. let spaces = 0;
  4. for (var i = 0; i < input.length; i++) {
  5. function closing(c) {
  6. return ['}', ']'].indexOf(c) >= 0;
  7. }
  8. function opening(c) {
  9. return ['{', '['].indexOf(c) >= 0;
  10. }
  11. let c = input[i];
  12. let previous = input[i-1];
  13. let next = input[i+1];
  14.  
  15. let comma = c == ',' && !closing(previous);
  16. if (closing(c)) {
  17. formatted += "\n";
  18. spaces -= 2;
  19. if (spaces > 0) {
  20. formatted += " ".repeat(spaces);
  21. }
  22. }
  23.  
  24. formatted += c
  25.  
  26. if (opening(c)) {
  27. formatted += "\n";
  28. spaces += 2;
  29. if (spaces > 0) {
  30. formatted += " ".repeat(spaces)
  31. }
  32. } else if (c == ':' && next != ' ' && !closing(next)) {
  33. formatted += " ";
  34. } else if (c == ',') {
  35. formatted += "\n";
  36. if (spaces > 0) {
  37. formatted += " ".repeat(spaces);
  38. }
  39. }
  40. }
  41. return formatted;
  42. }
RAW Paste Data