function jsonFormat() {
var text = $("#json1").val().split("\n").join(" ");
var t = [];
var tab = 0;
var rept=[];
var c='';
for (var i = 0, len = text.length; i < len; i++) {
c= text.charAt(i);
if (c === ' ' || c === '\t' || c === '\r' || c === '\n') {
continue;
}
switch(c){
case ':':
c=": ";
break;
case ',':
rept.length=tab<<2;
c = ",\n"+rept.join(' ');
break;
case '[':
case '{':
tab++;
rept.length=tab<<2;
c += "\n"+rept.join(' ');
break;
case ']':
case '}':
tab--;
rept.length=tab<<2;
c = "\n"+rept.join(' ')+c;
break;
}
t.push(c);
}
$("#json2").html(t.join('').replace(/\n/g,"<br/>").replace(/ /g," "));
}
public static String jsonFormat(String jsonStr) {
int len = jsonStr.length();
StringBuffer msg = new StringBuffer();
int tab = 0;
for (int i = 0; i < len; i++) {
char c = jsonStr.charAt(i);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
continue;
}
switch (c) {
case ':':
msg.append(c).append(" ");
break;
case ',':
msg.append(c).append("\n").append(StringUtils.repeat(' ', tab << 2));
break;
case '[':
case '{':
tab++;
msg.append(c).append("\n").append(StringUtils.repeat(' ', tab << 2));
break;
case ']':
case '}':
tab--;
msg.append("\n").append(StringUtils.repeat(' ', tab << 2)).append(c);
break;
default:
msg.append(c);
}
}
return msg.toString();
}