通常有些作后台数据查询,要把后台返回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
好!完事!但愿能帮到你字符串