<html>
<head>
<title>JSON Formater</title>
<style type="text/css">
body{
margin: 0px;
padding: 0px;
overflow: hidden;
}
</style>
<script type="text/javascript">
var JSONFormater = {
indentType: "\t",
source: false,
output: "",
format: function() {
if (document.getElementById("inputJSON").value.length == 0) {
alert("Empty source.");
return;
}
try {
eval("JSONFormater.source = " + document.getElementById("inputJSON").value + ";");
} catch (e) {
alert("Invalid JSON data.");
return;
}
this.indentType = this.selectedIndent();
this.iteratorChilds(this.source, 0, false);
this.clearTails();
document.getElementById("inputJSON").value = this.output;
this.output = "";
},
hasMembers: function(obj) {
for (var m in obj) return true;
return false;
},
isArray: function(obj) {
return obj.constructor == Array;
},
isString: function(obj) {
return obj.constructor == String;
},
iteratorChilds: function(obj, indent, isMember) {
if (this.isArray(obj)) {
this.output += "[\n";
for (var i = 0; i < obj.length; i++) {
this.iteratorChilds(obj[i], indent + 1, false);
}
this.clearTails();
this.output += this.currentIndent(indent);
this.output += "],\n";
} else if (this.hasMembers(obj)) {
if (!isMember) this.output += this.currentIndent(indent);
this.output += "{\n";
for (var e in obj) {
this.output += this.currentIndent(indent + 1);
this.output += (this.isString(e) ? "\"" + e + "\"" : e) + ": ";
this.iteratorChilds(obj[e], indent + 1, true);
}
this.clearTails();
this.output += this.currentIndent(indent);
this.output += "},\n";
} else {
if (!isMember) this.output += this.currentIndent(indent);
this.output += this.isString(obj) ? "\"" + obj + "\"" : obj;
this.output += ",\n";
}
},
currentIndent: function(ident) {
var it = "";
for (var i = 0; i < ident; i++) {
it += this.indentType;
}
return it;
},
clearTails: function() {
if (this.output.length > 2) this.output = this.output.substring(0, this.output.length - 2) + "\n";
},
selectedIndent: function() {
switch (document.getElementById("indentType").value) {
case "1":
return "\t";
case "2":
return " ";
case "3":
return " ";
case "4":
return " ";
case "8":
return " ";
}
}
};
window.onresize = function(){
document.getElementById("inputJSON").style.height = document.body.offsetHeight-30;
};
</script>
</head>
<body onload="document.getElementById('inputJSON').style.height = document.body.offsetHeight-30;">
<textarea id="inputJSON" style="width: 100%;" rows="15" style="overflow: both;"></textarea>
<div>
<input type="button" value="format" onclick="JSONFormater.format();" />
<select id="indentType">
<option value="1" selected="selected">indent with a tab character</option>
<option value="2">indent with 2 spaces</option>
<option value="3">indent with 3 spaces</option>
<option value="4">indent with 4 spaces</option>
<option value="8">indent with 8 spaces</option>
</select>
</div>
</body>
</html>