*页面格式化json
<!DOCTYPE html>
<html>
<head>
<title>测试页</title>
<style>
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; word-wrap: break-word; white-space: pre-wrap; width: 100%; height: 100%; overflow: auto;}
<!-- pre标签要设置长度和高度才能设置滚动条,pre-wrap为自动换行 -->
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>
</head>
<body>
<div>
<pre id="jsonStr1" style="width:50;"></pre>
<pre id="jsonStr2"></pre>
<pre id="jsonStr3"></pre>
</div>
<script type="text/javascript">
var songResJson={
"requestHead":{
"sign":"GM2EUi+hJV6VNi6Hss+eWxHA9YkAZ9FEREKKDIBLYe4XWmqsdc8qQj5La00xno+jZg+DCFoejnZovLiUa3Xs05MHaznTrs4gpLFFl77KZSA9Qdrl3FAMxv2f2lnY1pNVOwSbDENjgyk=",
"tradeDate":"2017-07-24 10:51:42",
"tradeType":"car",
"openID":"dXiao",
"tradeNo":"5506A722FD41B852E0530100007F6802AAAA",
"token":"dianxiao"
},
"toMobile":"18326113693",
"xmsContent":"您好!天安电话车险为您报价:交强险保费855元,商业险保费2583.91元,总计3438.91元,含 车损险(保额9.18万)1160.61元, 三者险(保额50万)1061.04元, 无法找到第三方特约险(保额0万)29.01元,不计免赔共333.25元。另代缴车船税300元。最终价格会受您既往理赔情况等因素影响,请以出单为准。如需详询请致电95505转3,尹慧慧(工号792594)为您服务",
"smsChannel":"04"
};
function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
};
document.getElementById("jsonStr1").innerHTML=JSON.stringify(songResJson,null,2);
document.getElementById("jsonStr2").innerHTML=JSON.stringify(songResJson,null,4);
document.getElementById("jsonStr3").innerHTML=syntaxHighlight(songResJson);
</script>
</body>
<html>
*页面格式化xml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生js格式化xml的方法</title>
</head>
<body>
<!--格式化后的xml写入的位置-->
<div id="writePlace"></div>
<script>
//格式化代码函数,已经用原生方式写好了不需要改动,直接引用就好
String.prototype.removeLineEnd = function () {
return this.replace(/(<.+?\s+?)(?:\n\s*?(.+?=".*?"))/g, '$1 $2')
}
function formatXml(text) {
//去掉多余的空格
text = '\n' + text.replace(/(<\w+)(\s.*?>)/g, function ($0, name, props) {
return name + ' ' + props.replace(/\s+(\w+=)/g, " $1");
}).replace(/>\s*?</g, ">\n<");
//把注释编码
text = text.replace(/\n/g, '\r').replace(/<!--(.+?)-->/g, function ($0, text) {
var ret = '<!--' + escape(text) + '-->';
//alert(ret);
return ret;
}).replace(/\r/g, '\n');
//调整格式
var rgx = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
var nodeStack = [];
var output = text.replace(rgx, function ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) {
var isClosed = (isCloseFull1 == '/') || (isCloseFull2 == '/' ) || (isFull1 == '/') || (isFull2 == '/');
//alert([all,isClosed].join('='));
var prefix = '';
if (isBegin == '!') {
prefix = getPrefix(nodeStack.length);
}
else {
if (isBegin != '/') {
prefix = getPrefix(nodeStack.length);
if (!isClosed) {
nodeStack.push(name);
}
}
else {
nodeStack.pop();
prefix = getPrefix(nodeStack.length);
}
}
var ret = '\n' + prefix + all;
return ret;
});
var prefixSpace = -1;
var outputText = output.substring(1);
//alert(outputText);
//把注释还原并解码,调格式
outputText = outputText.replace(/\n/g, '\r').replace(/(\s*)<!--(.+?)-->/g, function ($0, prefix, text) {
//alert(['[',prefix,']=',prefix.length].join(''));
if (prefix.charAt(0) == '\r')
prefix = prefix.substring(1);
text = unescape(text).replace(/\r/g, '\n');
var ret = '\n' + prefix + '<!--' + text.replace(/^\s*/mg, prefix) + '-->';
//alert(ret);
return ret;
});
return outputText.replace(/\s+$/g, '').replace(/\r/g, '\r\n');
}
function getPrefix(prefixIndex) {
var span = ' ';
var output = [];
for (var i = 0; i < prefixIndex; ++i) {
output.push(span);
}
return output.join('');
}
//引用示例部分
//(1)创建xml格式或者从后台拿到对应的xml格式
var originalXml = '<?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Dont forget me this weekend!</body> </note>';
//(2)调用formatXml函数,将xml格式进行格式化
var resultXml = formatXml(originalXml);
//(3)将格式化好后的formatXml写入页面中
document.getElementById("writePlace").innerHTML = "<xmp>"+resultXml+"</xmp>";
</script>
</body>
</html>
*后台格式化json
package com.tools;
/**
* 格式化输入工具类
*
* @author lizhgb
* @date 2015-10-14
* @Modified 2017-04-28
*
*/
public final class FormatUtil {
/**
* 打印输入到控制台
*
* @param jsonStr
* @author lizhgb
* @Date 2015-10-14 下午1:17:22
*/
public static void printJson(String jsonStr) {
System.out.println(formatJson(jsonStr));
}
/**
* 格式化
*
* @param jsonStr
* @return
* @author lizhgb
* @Date 2015-10-14 下午1:17:35
* @Modified 2017-04-28 下午8:55:35
*/
public static String formatJson(String jsonStr) {
if (null == jsonStr || "".equals(jsonStr))
return "";
StringBuilder sb = new StringBuilder();
char last = '\0';
char current = '\0';
int indent = 0;
boolean isInQuotationMarks = false;
for (int i = 0; i < jsonStr.length(); i++) {
last = current;
current = jsonStr.charAt(i);
switch (current) {
case '"':
if (last != '\\'){
isInQuotationMarks = !isInQuotationMarks;
}
sb.append(current);
break;
case '{':
case '[':
sb.append(current);
if (!isInQuotationMarks) {
sb.append("<br>");
indent++;
addIndentBlank(sb, indent);
}
break;
case '}':
case ']':
if (!isInQuotationMarks) {
sb.append("<br>");
indent--;
addIndentBlank(sb, indent);
}
sb.append(current);
break;
case ',':
sb.append(current);
if (last != '\\' && !isInQuotationMarks) {
sb.append("<br>");
addIndentBlank(sb, indent);
}
break;
default:
sb.append(current);
}
}
return sb.toString();
}
/**
* 添加space
*
* @param sb
* @param indent
* @author lizhgb
* @Date 2015-10-14 上午10:38:04
*/
private static void addIndentBlank(StringBuilder sb, int indent) {
for (int i = 0; i < indent; i++) {
sb.append(" ");
}
}
}