(编辑:jimmy 日期: 2025/11/5 浏览:2)
本文实例讲述了JavaScript格式化json和xml的方法。分享给大家供大家参考,具体如下:
格式化json实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生js格式化json的方法</title>
</head>
<body>
<!--格式化后的json写入的位置-->
<div id="writePlace"></div>
<script>
//格式化代码函数,已经用原生方式写好了不需要改动,直接引用就好
var formatJson = function (json, options) {
var reg = null,
formatted = '',
pad = 0,
PADDING = ' ';
options = options || {};
options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) "name": "binginsist", "sex": "男", "age": "25"};
//(2)调用formatJson函数,将json格式进行格式化
var resultJson = formatJson(originalJson);
//(3)将格式化好后的json写入页面中
document.getElementById("writePlace").innerHTML = '<pre>' +resultJson + '<pre/>';
</script>
</body>
</html>
这里使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码,可得如下运行结果:
{
"name":"binginsist",
"sex":"男",
"age":"25"
}
格式化xml实例
在格式化XML时后台需要对返回数据做一下处理:
StringEscapeUtils.escapeHtml(po.getMsgBody())
<!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(/(<.+".*"))/g, '$1 $2')
}
function formatXml(text) {
//去掉多余的空格
text = '\n' + text.replace(/(<\w+)(\s.*" $1");
}).replace(/>\s*">\n<");
//把注释编码
text = text.replace(/\n/g, '\r').replace(/<!--(.+"1.0""writePlace").innerHTML = '<pre>' +resultXml + '<pre/>';
</script>
</body>
</html>
这里使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码,可得如下运行结果:
Tove
Jani
Reminder
Dont forget me this weekend!
PS:这里再为大家提供几款关于xml与json操作的在线工具供大家参考使用:
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
在线格式化XML/在线压缩XML:
http://tools.jb51.net/code/xmlformat
XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress
在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans
更多关于JavaScript相关内容可查看本站专题:《JavaScript操作XML文件技巧总结》、《JavaScript中json操作技巧总结》、《JavaScript字符与字符串操作技巧总结》、《JavaScript错误与调试技巧总结》及《JavaScript数据结构与算法技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。