前言:
最近做的項目中遇到個需要在前端頁面中將某個設備需要的數據格式展示出來,方便用戶配置。一開始單純的將數據格式寫入到pre標簽中, 但是通過pre標簽寫入的數據格式在代碼可視化上不是很優雅。由於上述原因,所以就創建了一個全局的數據格式配置文件,通過es6 中的模板字符串來實現,這樣就解決了代碼可視化不優雅的問題。但是后面又增加了一個動態數據格式的需求,這樣一來就不能通過模板字符串來 解決了,所以就有了這篇文章中講述的通過js格式畫JSON數據的方案,這篇文章旨在記錄方案實現的方法,方便自己 以后遇到同樣的需求直接粘貼復制,同時也希望能夠幫助到遇到和我一樣需求的碼農。
示例效果圖如下:

預覽地址:js實現格式化JSON數據
js格式化JSON數據的方法如下,其中各塊代碼具體表示的什么意思及完成的功能都通過注釋的方式進行了詳細說明。
1 // 格式方法 2 // 公共方法 3 function transitionJsonToString (jsonObj, callback) { 4 // 轉換后的jsonObj受體對象 5 var _jsonObj = null; 6 // 判斷傳入的jsonObj對象是不是字符串,如果是字符串需要先轉換為對象,再轉換為字符串,這樣做是為了保證轉換后的字符串為雙引號 7 if (Object.prototype.toString.call(jsonObj) !== "[object String]") { 8 try { 9 _jsonObj = JSON.stringify(jsonObj); 10 } catch (error) { 11 // 轉換失敗錯誤信息 12 console.error('您傳遞的json數據格式有誤,請核對...'); 13 console.error(error); 14 callback(error); 15 } 16 } else { 17 try { 18 jsonObj = jsonObj.replace(/(\')/g, '\"'); 19 _jsonObj = JSON.stringify(JSON.parse(jsonObj)); 20 } catch (error) { 21 // 轉換失敗錯誤信息 22 console.error('您傳遞的json數據格式有誤,請核對...'); 23 console.error(error); 24 callback(error); 25 } 26 } 27 return _jsonObj; 28 } 29 // callback為數據格式化錯誤的時候處理函數 30 function formatJson (jsonObj, callback) { 31 // 正則表達式匹配規則變量 32 var reg = null; 33 // 轉換后的字符串變量 34 var formatted = ''; 35 // 換行縮進位數 36 var pad = 0; 37 // 一個tab對應空格位數 38 var PADDING = ' '; 39 // json對象轉換為字符串變量 40 var jsonString = transitionJsonToString(jsonObj, callback); 41 if (!jsonString) { 42 return jsonString; 43 } 44 // 存儲需要特殊處理的字符串段 45 var _index = []; 46 // 存儲需要特殊處理的“再數組中的開始位置變量索引 47 var _indexStart = null; 48 // 存儲需要特殊處理的“再數組中的結束位置變量索引 49 var _indexEnd = null; 50 // 將jsonString字符串內容通過\r\n符分割成數組 51 var jsonArray = []; 52 // 正則匹配到{,}符號則在兩邊添加回車換行 53 jsonString = jsonString.replace(/([\{\}])/g, '\r\n$1\r\n'); 54 // 正則匹配到[,]符號則在兩邊添加回車換行 55 jsonString = jsonString.replace(/([\[\]])/g, '\r\n$1\r\n'); 56 // 正則匹配到,符號則在兩邊添加回車換行 57 jsonString = jsonString.replace(/(\,)/g, '$1\r\n'); 58 // 正則匹配到要超過一行的換行需要改為一行 59 jsonString = jsonString.replace(/(\r\n\r\n)/g, '\r\n'); 60 // 正則匹配到單獨處於一行的,符號時需要去掉換行,將,置於同行 61 jsonString = jsonString.replace(/\r\n\,/g, ','); 62 // 特殊處理雙引號中的內容 63 jsonArray = jsonString.split('\r\n'); 64 jsonArray.forEach(function (node, index) { 65 // 獲取當前字符串段中"的數量 66 var num = node.match(/\"/g) ? node.match(/\"/g).length : 0; 67 // 判斷num是否為奇數來確定是否需要特殊處理 68 if (num % 2 && !_indexStart) { 69 _indexStart = index 70 } 71 if (num % 2 && _indexStart && _indexStart != index) { 72 _indexEnd = index 73 } 74 // 將需要特殊處理的字符串段的其實位置和結束位置信息存入,並對應重置開始時和結束變量 75 if (_indexStart && _indexEnd) { 76 _index.push({ 77 start: _indexStart, 78 end: _indexEnd 79 }) 80 _indexStart = null 81 _indexEnd = null 82 } 83 }) 84 // 開始處理雙引號中的內容,將多余的"去除 85 _index.reverse().forEach(function (item, index) { 86 var newArray = jsonArray.slice(item.start, item.end + 1) 87 jsonArray.splice(item.start, item.end + 1 - item.start, newArray.join('')) 88 }) 89 // 獎處理后的數組通過\r\n連接符重組為字符串 90 jsonString = jsonArray.join('\r\n'); 91 // 將匹配到:后為回車換行加大括號替換為冒號加大括號 92 jsonString = jsonString.replace(/\:\r\n\{/g, ':{'); 93 // 將匹配到:后為回車換行加中括號替換為冒號加中括號 94 jsonString = jsonString.replace(/\:\r\n\[/g, ':['); 95 // 將上述轉換后的字符串再次以\r\n分割成數組 96 jsonArray = jsonString.split('\r\n'); 97 // 將轉換完成的字符串根據PADDING值來組合成最終的形態 98 jsonArray.forEach(function (item, index) { 99 console.log(item) 100 var i = 0; 101 // 表示縮進的位數,以tab作為計數單位 102 var indent = 0; 103 // 表示縮進的位數,以空格作為計數單位 104 var padding = ''; 105 if (item.match(/\{$/) || item.match(/\[$/)) { 106 // 匹配到以{和[結尾的時候indent加1 107 indent += 1 108 } else if (item.match(/\}$/) || item.match(/\]$/) || item.match(/\},$/) || item.match(/\],$/)) { 109 // 匹配到以}和]結尾的時候indent減1 110 if (pad !== 0) { 111 pad -= 1 112 } 113 } else { 114 indent = 0 115 } 116 for (i = 0; i < pad; i++) { 117 padding += PADDING 118 } 119 formatted += padding + item + '\r\n' 120 pad += indent 121 }) 122 // 返回的數據需要去除兩邊的空格 123 return formatted.trim(); 124 }
