json格式化小工具,原生js编写,直接上代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>原生js格式化json的方法</title> 6 <script> 7 //格式化代码函数,已经用原生方式写好了不需要改动,直接引用就好 8 var formatJson = function (json) { 9 var formatted = ‘‘, //转换后的json字符串 10 padIdx = 0, //换行后是否增减PADDING的标识 11 PADDING = ‘ ‘; //4个空格符 12 /** 13 * 将对象转化为string 14 */ 15 if (typeof json !== ‘string‘) { 16 json = JSON.stringify(json); 17 } 18 /** 19 *利用正则类似将{‘name‘:‘ccy‘,‘age‘:18,‘info‘:[‘address‘:‘wuhan‘,‘interest‘:‘playCards‘]} 20 *---> \r\n{\r\n‘name‘:‘ccy‘,\r\n‘age‘:18,\r\n 21 *‘info‘:\r\n[\r\n‘address‘:‘wuhan‘,\r\n‘interest‘:‘playCards‘\r\n]\r\n}\r\n 22 */ 23 json = json.replace(/([\{\}])/g, ‘\r\n$1\r\n‘) 24 .replace(/([\[\]])/g, ‘\r\n$1\r\n‘) 25 .replace(/(\,)/g, ‘$1\r\n‘) 26 .replace(/(\r\n\r\n)/g, ‘\r\n‘) 27 .replace(/\r\n\,/g, ‘,‘); 28 /** 29 * 根据split生成数据进行遍历,一行行判断是否增减PADDING 30 */ 31 (json.split(‘\r\n‘)).forEach(function (node, index) { 32 var indent = 0, 33 padding = ‘‘; 34 if (node.match(/\{$/) || node.match(/\[$/)) indent = 1; 35 else if (node.match(/\}/) || node.match(/\]/)) padIdx = padIdx !== 0 ? --padIdx : padIdx; 36 else indent = 0; 37 for (var i = 0; i < padIdx; i++) padding += PADDING; 38 formatted += padding + node + ‘\r\n‘; 39 padIdx += indent; 40 console.log(‘index:‘+index+‘,indent:‘+indent+‘,padIdx:‘+padIdx+‘,node-->‘+node); 41 }); 42 return formatted; 43 }; 44 //引用示例部分 45 //var originalJson = {‘name‘:‘ccy‘,‘age‘:18,‘info‘:[{‘address‘:‘wuhan‘},{‘interest‘:‘playCards‘}]}; 53 var showJson = function(){ 54 var originalJson = document.getElementById(‘inputJson‘).value; 55 console.log(originalJson); 56 //(2)调用formatJson函数,将json格式进行格式化 57 var resultJson = formatJson(originalJson); 60 document.getElementById(‘out‘).innerHTML = resultJson; 61 } 62 </script> 63 </head> 64 <body> 65 <span style="position:absolute;left:0px;top:20px;font-size: 20px;font-family: ‘微软雅黑‘;color: #2F4F4F;">输入json</span> 66 <textarea style="position:absolute;left:0px;top:80px;width:40%;height:80%;" cols="50" rows="20" id="inputJson"></textarea> 67 <span style="position:absolute;left:55%;top:20px;font-size: 20px;font-family: ‘微软雅黑‘;color: #2F4F4F;">查看结果</span> 68 <textarea style="position:absolute;left:55%;top:80px;width:40%;height:80%;display: " id="out"></textarea> 69 <div style="position:absolute;left:45%;top:12%;width:6%;height:4%;"> 70 <input type="button" value="提交" onclick="showJson();"> 71 </div> 73 </body> 74 </html>
原文地址:https://www.cnblogs.com/ccylovehs/p/9253237.html
时间: 2024-10-07 17:24:53