Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function beautifyJSON(input) {
- var formatted = '';
- let spaces = 0;
- for (var i = 0; i < input.length; i++) {
- function closing(c) {
- return ['}', ']'].indexOf(c) >= 0;
- }
- function opening(c) {
- return ['{', '['].indexOf(c) >= 0;
- }
- let c = input[i];
- let previous = input[i-1];
- let next = input[i+1];
- let comma = c == ',' && !closing(previous);
- if (closing(c)) {
- formatted += "\n";
- spaces -= 2;
- if (spaces > 0) {
- formatted += " ".repeat(spaces);
- }
- }
- formatted += c
- if (opening(c)) {
- formatted += "\n";
- spaces += 2;
- if (spaces > 0) {
- formatted += " ".repeat(spaces)
- }
- } else if (c == ':' && next != ' ' && !closing(next)) {
- formatted += " ";
- } else if (c == ',') {
- formatted += "\n";
- if (spaces > 0) {
- formatted += " ".repeat(spaces);
- }
- }
- }
- return formatted;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement