一般有些做后台數據查詢,要把后台返回json數據展示到頁面上,如果需要展示樣式更清晰、直觀、一目了然,就要用到html+css+js實現這個小功能
一、css代碼
pre {outline: 1px solid #ccc; } .string { color: green; } .number { color: darkorange; } .boolean { color: blue; } .null { color: magenta; } .key { color: red; }
二、html部分代碼
<pre id="jsonShow"></pre> //必須使用這個標簽,否則顯示的json沒有格式化
三、js部分
1、首先封裝一段展示json樣式的代碼(我沒有加行號,你可以直接復制拿用)
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>'; }); }
2、函數調用
$('#jsonShow').html(jsonShowFn(json)) //json為要展示到頁面的數據
四、效果
因項目返回查詢數據量比較大,我只展示部分代碼樣式
在后台返回數據過程中,返回的數據為字符串形式的json,如果你也遇到這種情況,先把返回數據轉成json形式,用到 JSON.parse()這個方法;若沒這種情況,可直接使用
好!完事!希望能幫到你