前提條件
從后台獲得json字符串或對象,或者自定義json字符串或對象。
原理
JSON.stringify本身就可以將JSON格式化,具體的用法是:
JSON.stringify(res, null, 2); //res是要JSON化的對象,2是spacing的格式,用於縮進
操作步驟
1、定義js函數
1 function syntaxHighlight(json) { 2 if (typeof json != 'string') { 3 json = JSON.stringify(json, undefined, 2); 4 } 5 json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); 6 return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, 7 function(match) { 8 var cls = 'number'; 9 if (/^"/.test(match)) { 10 if (/:$/.test(match)) { 11 cls = 'key'; 12 } else { 13 cls = 'string'; 14 } 15 } else if (/true|false/.test(match)) { 16 cls = 'boolean'; 17 } else if (/null/.test(match)) { 18 cls = 'null'; 19 } 20 return '<span class="' + cls + '">' + match + '</span>'; 21 } 22 ); 23 }
這個函數的參數json,可以是一個json字符串,也可以是一個對象。如果是一個json字符串,在函數中將不經過JSON.stringify的格式化,也就不能產生縮進的效果,除非字符串本身就含有縮進。因此,盡量給這個函數傳遞一個對象。、
此外,這個函數將一個json對象轉化為一段html代碼,因此還需要等於相應的css樣式。
2、定義css樣式
1 <style> 2 pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; } 3 .string { color: green; } /*字符串的樣式*/ 4 .number { color: darkorange; } /*數字的樣式*/ 5 .boolean { color: blue; } /*布爾型數據的樣式*/ 6 .null { color: magenta; } /*null值的樣式*/ 7 .key { color: red; } /*key值的樣式*/ 8 </style>
3、定義html內容
在html文件中添加一個pre標簽,用於顯示格式化的json字符串
1 <pre id="result"></pre>
然后調用js代碼,對該pre標簽進行初始化即可
1 $('#result').html(syntaxHighlight(res)); 2 //其中res最好是對象,這樣在函數中就可進行縮進等格式化處理。