通常有些作後臺數據查詢,要把後臺返回json數據展現到頁面上,若是須要展現樣式更清晰、直觀、一目瞭然,就要用到html+css+js實現這個小功能css
1、css代碼html
pre {outline: 1px solid #ccc; } .string { color: green; } .number { color: darkorange; } .boolean { color: blue; } .null { color: magenta; } .key { color: red; }
2、html部分代碼json
<pre id="jsonShow"></pre> //必須使用這個標籤,不然顯示的json沒有格式化
3、js部分函數
一、首先封裝一段展現json樣式的代碼(我沒有加行號,你能夠直接複製拿用)spa
jsonShowFn(json){ if (!json.match("^\{(.+:.+,*){1,}\}$")) { return json //判斷是不是json數據,不是直接返回 } if (typeof json != 'string') { json = JSON.stringify(json, undefined, 2); } json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) { var cls = 'number'; if (/^"/.test(match)) { if (/:$/.test(match)) { cls = 'key'; } else { cls = 'string'; } } else if (/true|false/.test(match)) { cls = 'boolean'; } else if (/null/.test(match)) { cls = 'null'; } return '<span class="' + cls + '">' + match + '</span>'; }); }
二、函數調用code
$('#jsonShow').html(jsonShowFn(json)) //json爲要展現到頁面的數據
4、效果htm
因項目返回查詢數據量比較大,我只展現部分代碼樣式blog
在後臺返回數據過程當中,返回的數據爲字符串形式的json,若是你也遇到這種狀況,先把返回數據轉成json形式,用到 JSON.parse()這個方法;若沒這種狀況,可直接使用html+css+js
好!完事!但願能幫到你字符串