var formatJson = function(json, options) {
var reg = null,
formatted = "",
pad = 0,
PADDING = " ";
options = options || {};
options.newlineAfterColonIfBeforeBraceOrBracket =
options.newlineAfterColonIfBeforeBraceOrBracket === true ? true : false;
options.spaceAfterColon = options.spaceAfterColon === false ? false : true;
if (typeof json !== "string") {
json = JSON.stringify(json);
}
json = JSON.parse(json);
json = JSON.stringify(json);
reg = /([\{\}])/g;
json = json.replace(reg, "\r\n$1\r\n");
reg = /([\[\]])/g;
json = json.replace(reg, "\r\n$1\r\n");
reg = /(\,)/g;
json = json.replace(reg, "$1\r\n");
reg = /(\r\n\r\n)/g;
json = json.replace(reg, "\r\n");
reg = /\r\n\,/g;
json = json.replace(reg, ",");
if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
reg = /\:\r\n\{/g;
json = json.replace(reg, ":{");
reg = /\:\r\n\[/g;
json = json.replace(reg, ":[");
}
if (options.spaceAfterColon) {
reg = /\:/g;
json = json.replace(reg, ": ");
}
$.each(json.split("\r\n"), function(index, node) {
var i = 0,
indent = 0,
padding = "";
if (node.match(/\{$/) || node.match(/\[$/)) {
indent = 1;
} else if (node.match(/\}/) || node.match(/\]/)) {
if (pad !== 0) {
pad -= 1;
}
} else {
indent = 0;
}
for (i = 0; i < pad; i++) {
padding += PADDING;
}
formatted += padding + node + "\r\n";
pad += indent;
});
return formatted;
};
var json = {};
json = {
a: {
aa: [
1,
2,
{ aaa: "abc", bbb: "defgh", ccc: 987 },
[100, 200, 300, { one: 1, two: "ii", three: "Three" }, 1000]
],
bb: "xyz",
ccc: 777
},
b: ["qqq", "www", "eee"],
c: "hello",
d: 12345
};
$("#formattedJson1").text(formatJson(json));
json =
'{ "a": { "aa": [ 1, 2, { "aaa": "abc",' +
' "bbb": "defgh", "ccc": 987 }, [ 100, ' +
'200, 300 , { "one": 1, "two" : "ii", "three" ' +
': "Three" }, 1000 ]' +
" ], " +
' "bb": "xyz", "ccc": 777 }, "b": [ "qqq", "www", ' +
'"eee" ], "c": "hello", "d": 12345 }';
$("#formattedJson2").text(formatJson(json));