一般有些做后台数据查询,要把后台返回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()这个方法;若没这种情况,可直接使用
好!完事!希望能帮到你