在工做中一直看各位前輩的博客解決各類問題,對個人幫助很大,很是感謝! 以前一直比較忙沒有寫博客,終於過年有了點空閒時間,能夠把本身積累的東西分享下,筆記中的部分函數不是本身寫的,都是工做中一點點積累的,因爲時間已久比較零散找不到對應的主人了,無法註明出處還請見諒。咱們常常遇到從後代拿到的沒有格式化的json和xml,須要格式化好了之後顯示在頁面上,這篇文章但願可讓您更加方便的實現這個需求。本文的代碼使用原生方式編寫,不須要引用其餘插件,能夠在傳統項目和自動化項目中直接使用。爲了方便測試,我整理了下,只要建一個空的html,將全部的代碼copy進去,本地打開就能夠查看效果。作好的html在GitHub上也放了一份,之後有時間就會將本身整理的筆記放到上面,地址以下: https://github.com/binginsist/binginsistNote
格式化json實例
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>原生js格式化json的方法</title> 6 </head> 7 <body> 8 <!--格式化後的json寫入的位置--> 9 <div id="writePlace"></div> 10 <script> 11 //格式化代碼函數,已經用原生方式寫好了不須要改動,直接引用就好 12 var formatJson = function (json, options) { 13 var reg = null, 14 formatted = '', 15 pad = 0, 16 PADDING = ' '; 17 options = options || {}; 18 options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false; 19 options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true; 20 if (typeof json !== 'string') { 21 json = JSON.stringify(json); 22 } else { 23 json = JSON.parse(json); 24 json = JSON.stringify(json); 25 } 26 reg = /([\{\}])/g; 27 json = json.replace(reg, '\r\n$1\r\n'); 28 reg = /([\[\]])/g; 29 json = json.replace(reg, '\r\n$1\r\n'); 30 reg = /(\,)/g; 31 json = json.replace(reg, '$1\r\n'); 32 reg = /(\r\n\r\n)/g; 33 json = json.replace(reg, '\r\n'); 34 reg = /\r\n\,/g; 35 json = json.replace(reg, ','); 36 if (!options.newlineAfterColonIfBeforeBraceOrBracket) { 37 reg = /\:\r\n\{/g; 38 json = json.replace(reg, ':{'); 39 reg = /\:\r\n\[/g; 40 json = json.replace(reg, ':['); 41 } 42 if (options.spaceAfterColon) { 43 reg = /\:/g; 44 json = json.replace(reg, ':'); 45 } 46 (json.split('\r\n')).forEach(function (node, index) { 47 var i = 0, 48 indent = 0, 49 padding = ''; 50 51 if (node.match(/\{$/) || node.match(/\[$/)) { 52 indent = 1; 53 } else if (node.match(/\}/) || node.match(/\]/)) { 54 if (pad !== 0) { 55 pad -= 1; 56 } 57 } else { 58 indent = 0; 59 } 60 61 for (i = 0; i < pad; i++) { 62 padding += PADDING; 63 } 64 65 formatted += padding + node + '\r\n'; 66 pad += indent; 67 } 68 ); 69 return formatted; 70 }; 71 //引用示例部分 72 //(1)建立json格式或者從後臺拿到對應的json格式 73 var originalJson = {"name": "binginsist", "sex": "男", "age": "25"}; 74 //(2)調用formatJson函數,將json格式進行格式化 75 var resultJson = formatJson(originalJson); 76 //(3)將格式化好後的json寫入頁面中 77 document.getElementById("writePlace").innerHTML = '<pre>' +resultJson + '<pre/>'; 78 </script> 79 </body> 80 </html>
格式化xml實例:html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>原生js格式化xml的方法</title> 6 </head> 7 <body> 8 <!--格式化後的xml寫入的位置--> 9 <div id="writePlace"></div> 10 <script> 11 //格式化代碼函數,已經用原生方式寫好了不須要改動,直接引用就好 12 String.prototype.removeLineEnd = function () { 13 return this.replace(/(<.+?\s+?)(?:\n\s*?(.+?=".*?"))/g, '$1 $2') 14 } 15 function formatXml(text) { 16 //去掉多餘的空格 17 text = '\n' + text.replace(/(<\w+)(\s.*?>)/g, function ($0, name, props) { 18 return name + ' ' + props.replace(/\s+(\w+=)/g, " $1"); 19 }).replace(/>\s*?</g, ">\n<"); 20 21 //把註釋編碼 22 text = text.replace(/\n/g, '\r').replace(/<!--(.+?)-->/g, function ($0, text) { 23 var ret = '<!--' + escape(text) + '-->'; 24 //alert(ret); 25 return ret; 26 }).replace(/\r/g, '\n'); 27 28 //調整格式 29 var rgx = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg; 30 var nodeStack = []; 31 var output = text.replace(rgx, function ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) { 32 var isClosed = (isCloseFull1 == '/') || (isCloseFull2 == '/' ) || (isFull1 == '/') || (isFull2 == '/'); 33 //alert([all,isClosed].join('=')); 34 var prefix = ''; 35 if (isBegin == '!') { 36 prefix = getPrefix(nodeStack.length); 37 } 38 else { 39 if (isBegin != '/') { 40 prefix = getPrefix(nodeStack.length); 41 if (!isClosed) { 42 nodeStack.push(name); 43 } 44 } 45 else { 46 nodeStack.pop(); 47 prefix = getPrefix(nodeStack.length); 48 } 49 50 } 51 var ret = '\n' + prefix + all; 52 return ret; 53 }); 54 55 var prefixSpace = -1; 56 var outputText = output.substring(1); 57 //alert(outputText); 58 59 //把註釋還原並解碼,調格式 60 outputText = outputText.replace(/\n/g, '\r').replace(/(\s*)<!--(.+?)-->/g, function ($0, prefix, text) { 61 //alert(['[',prefix,']=',prefix.length].join('')); 62 if (prefix.charAt(0) == '\r') 63 prefix = prefix.substring(1); 64 text = unescape(text).replace(/\r/g, '\n'); 65 var ret = '\n' + prefix + '<!--' + text.replace(/^\s*/mg, prefix) + '-->'; 66 //alert(ret); 67 return ret; 68 }); 69 70 return outputText.replace(/\s+$/g, '').replace(/\r/g, '\r\n'); 71 } 72 function getPrefix(prefixIndex) { 73 var span = ' '; 74 var output = []; 75 for (var i = 0; i < prefixIndex; ++i) { 76 output.push(span); 77 } 78 79 return output.join(''); 80 } 81 82 //引用示例部分 83 //(1)建立xml格式或者從後臺拿到對應的xml格式 84 var originalXml = '<?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Dont forget me this weekend!</body> </note>'; 85 //(2)調用formatXml函數,將xml格式進行格式化 86 var resultXml = formatXml(originalXml); 87 //(3)將格式化好後的formatXml寫入頁面中 88 document.getElementById("writePlace").innerHTML = '<pre>' +resultXml + '<pre/>'; 89 </script> 90 </body> 91 </html>