JS实现json格式美化【工具包系列】

时间:2023-01-28 07:54:37
 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>json格式美化</title>
</head>
<body>

<form id="form1" name="form1">
<textarea name="sourcejson" id="sourcejson" cols="80" rows="30"></textarea>
<input type="button" onclick="formatJson();" value="美化"/>
<textarea name="targetjson" id="targetjson" cols="80" rows="30"> </textarea>
</form>
</body>

<script type="text/javascript">
function repeat(s, count) {
return new Array(count + 1).join(s);
}

function formatJson() {

var json= document.form1.sourcejson.value;

var i = 0,
len = 0,
tab = " ",
targetJson = "",
indentLevel = 0,
inString = false,
currentChar = null;


for (i = 0, len = json.length; i < len; i += 1) {
currentChar = json.charAt(i);

switch (currentChar) {
case '{':
case '[':
if (!inString) {
targetJson += currentChar + "\n" + repeat(tab, indentLevel + 1);
indentLevel += 1;
} else {
targetJson += currentChar;
}
break;
case '}':
case ']':
if (!inString) {
indentLevel -= 1;
targetJson += "\n" + repeat(tab, indentLevel) + currentChar;
} else {
targetJson += currentChar;
}
break;
case ',':
if (!inString) {
targetJson += ",\n" + repeat(tab, indentLevel);
} else {
targetJson += currentChar;
}
break;
case ':':
if (!inString) {
targetJson += ": ";
} else {
targetJson += currentChar;
}
break;
case ' ':
case "\n":
case "\t":
if (inString) {
targetJson += currentChar;
}
break;
case '"':
if (i > 0 && json.charAt(i - 1) !== '\\') {
inString = !inString;
}
targetJson += currentChar;
break;
default:
targetJson += currentChar;
break;
}
}
document.form1.targetjson.value=targetJson;
return;
}
</script>

</html>

注意:不要使用div作为输出容器,因为标签不会被执行。
运行结果
JS实现json格式美化【工具包系列】