html页面展示Json样式
生活随笔
收集整理的這篇文章主要介紹了
html页面展示Json样式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一般有些做后臺(tái)數(shù)據(jù)查詢,要把后臺(tái)返回json數(shù)據(jù)展示到頁面上,如果需要展示樣式更清晰、直觀、一目了然,就要用到html+css+js實(shí)現(xiàn)這個(gè)小功能
一、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> //必須使用這個(gè)標(biāo)簽,否則顯示的json沒有格式化?
三、js部分
1、首先封裝一段展示json樣式的代碼(我沒有加行號(hào),你可以直接復(fù)制拿用)
jsonShowFn(json){if (!json.match("^\{(.+:.+,*){1,}\}$")) {return json //判斷是否是json數(shù)據(jù),不是直接返回 }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、函數(shù)調(diào)用
$('#jsonShow').html(jsonShowFn(json)) //json為要展示到頁面的數(shù)據(jù)?
四、效果
因項(xiàng)目返回查詢數(shù)據(jù)量比較大,我只展示部分代碼樣式
在后臺(tái)返回?cái)?shù)據(jù)過程中,返回的數(shù)據(jù)為字符串形式的json,如果你也遇到這種情況,先把返回?cái)?shù)據(jù)轉(zhuǎn)成json形式,用到?JSON.parse()這個(gè)方法;若沒這種情況,可直接使用
?
好!完事!希望能幫到你
?
轉(zhuǎn)載于:https://www.cnblogs.com/shizk/p/9579962.html
總結(jié)
以上是生活随笔為你收集整理的html页面展示Json样式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python-基础知识
- 下一篇: 安装asterisk 时遇到的报错情况,