Skip to content

Instantly share code, notes, and snippets.

@aneelkkhatri
Last active October 19, 2018 11:26
Show Gist options
  • Save aneelkkhatri/2ff90bc914b491e4d82208c80a67dfff to your computer and use it in GitHub Desktop.
Save aneelkkhatri/2ff90bc914b491e4d82208c80a67dfff to your computer and use it in GitHub Desktop.
Stringify-Beautify JSON
function beautify(o, dl) {
function beautifyStringify(b, t) {
if (b === null || typeof b != "object") {
return JSON.stringify(b);
}
var sp = "";
for (var i = 0; i < t; ++i) sp += dl;
var sp1 = sp + dl;
var res = "";
if (b instanceof Array) {
res = "[\n" + b.map(function(o) {
return sp1 + beautifyStringify(o, t + 1);
}).join(",\n") + "\n" + sp + "]";
} else {
res = "{\n" + Object.keys(b).map(function(k) {
var o = b[k];
return sp1 + '"' + k + "\": " + beautifyStringify(o, t + 1);
}).join(",\n") + "\n" + sp + "}";
}
return res;
}
dl = dl ? dl : " ";
return beautifyStringify(o, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment