国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 語(yǔ)言 > JavaScript > 正文

JavaScript格式化json和xml的方法示例

2024-05-06 15:42:58
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(shí)例講述了JavaScript格式化json和xml的方法。分享給大家供大家參考,具體如下:

格式化json實(shí)例

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>原生js格式化json的方法</title></head><body><!--格式化后的json寫(xiě)入的位置--><div id="writePlace"></div><script> //格式化代碼函數(shù),已經(jīng)用原生方式寫(xiě)好了不需要改動(dòng),直接引用就好 var formatJson = function (json, options) {  var reg = null,    formatted = '',    pad = 0,    PADDING = ' ';  options = options || {};  options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;  options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;  if (typeof json !== 'string') {   json = JSON.stringify(json);  } else {   json = JSON.parse(json);   json = JSON.stringify(json);  }  reg = /([/{/}])/g;  json = json.replace(reg, '/r/n$1/r/n');  reg = /([/[/]])/g;  json = json.replace(reg, '/r/n$1/r/n');  reg = /(/,)/g;  json = json.replace(reg, '$1/r/n');  reg = /(/r/n/r/n)/g;  json = json.replace(reg, '/r/n');  reg = //r/n/,/g;  json = json.replace(reg, ',');  if (!options.newlineAfterColonIfBeforeBraceOrBracket) {   reg = //:/r/n/{/g;   json = json.replace(reg, ':{');   reg = //:/r/n/[/g;   json = json.replace(reg, ':[');  }  if (options.spaceAfterColon) {   reg = //:/g;   json = json.replace(reg, ':');  }  (json.split('/r/n')).forEach(function (node, index) {     var i = 0,       indent = 0,       padding = '';     if (node.match(//{$/) || node.match(//[$/)) {      indent = 1;     } else if (node.match(//}/) || node.match(//]/)) {      if (pad !== 0) {       pad -= 1;      }     } else {      indent = 0;     }     for (i = 0; i < pad; i++) {      padding += PADDING;     }     formatted += padding + node + '/r/n';     pad += indent;    }  );  return formatted; }; //引用示例部分 //(1)創(chuàng)建json格式或者從后臺(tái)拿到對(duì)應(yīng)的json格式 var originalJson = {"name": "binginsist", "sex": "男", "age": "25"}; //(2)調(diào)用formatJson函數(shù),將json格式進(jìn)行格式化 var resultJson = formatJson(originalJson); //(3)將格式化好后的json寫(xiě)入頁(yè)面中 document.getElementById("writePlace").innerHTML = '<pre>' +resultJson + '<pre/>';</script></body></html>

這里使用在線(xiàn)HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.Vevb.com/code/HtmlJsRun測(cè)試上述代碼,可得如下運(yùn)行結(jié)果:

{
    "name":"binginsist",
    "sex":"男",
    "age":"25"
}

格式化xml實(shí)例

在格式化XML時(shí)后臺(tái)需要對(duì)返回?cái)?shù)據(jù)做一下處理:

StringEscapeUtils.escapeHtml(po.getMsgBody())
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>原生js格式化xml的方法</title></head><body><!--格式化后的xml寫(xiě)入的位置--><div id="writePlace"></div><script> //格式化代碼函數(shù),已經(jīng)用原生方式寫(xiě)好了不需要改動(dòng),直接引用就好 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');  //調(diào)整格式  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);  //把注釋還原并解碼,調(diào)格式  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)創(chuàng)建xml格式或者從后臺(tái)拿到對(duì)應(yīng)的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)調(diào)用formatXml函數(shù),將xml格式進(jìn)行格式化 var resultXml = formatXml(originalXml); //(3)將格式化好后的formatXml寫(xiě)入頁(yè)面中 document.getElementById("writePlace").innerHTML = '<pre>' +resultXml + '<pre/>';</script></body></html>            
發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 通河县| 云林县| 庐江县| 武义县| 阿拉善右旗| 怀柔区| 渝北区| 青川县| 贵德县| 清河县| 镇江市| 芒康县| 茌平县| 周宁县| 吉首市| 商水县| 太康县| 安平县| 新宾| 龙山县| 新河县| 闽侯县| 台中县| 宁化县| 绵阳市| 中西区| 津南区| 大石桥市| 东源县| 桂阳县| 武隆县| 贺州市| 龙泉市| 枣强县| 龙川县| 边坝县| 台江县| 敖汉旗| 浦江县| 山西省| 台江县|