一般有些做后台数据查询,要把后台返回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样式的代码
1 function jsonShowFn(json){ 2 if(!json.match("^\{(.+:.+,*){1,}\}$")){ //如果不是json 直接返回 3 return json 4 } 5 if (typeof json != 'string') { 6 json = JSON.stringify(json, undefined, 2); 7 } 8 json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); 9 return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) { 10 var cls = 'number'; 11 if (/^"/.test(match)) { 12 if (/:$/.test(match)) { 13 cls = 'key'; 14 } else { 15 cls = 'string'; 16 } 17 } else if (/true|false/.test(match)) { 18 cls = 'boolean'; 19 } else if (/null/.test(match)) { 20 cls = 'null'; 21 } 22 return '<span class="' + cls + '">' + match + '</span>'; 23 }); 24 }
2、函数调用
$('#jsonShow').html(jsonShowFn(json)) //json为要展示到页面是数据
四、效果
因项目返回查询数据量比较大,我只展示部分代码样式
在后台返回数据过程中,返回的数据为字符串形式的json,如果你也遇到这种情况,先把返回数据转成json形式,用到 JSON.parse()这个方法;若没这种情况,可直接使用
好!完事!希望能帮到你