背景:
有時(shí)候我們需要將json數(shù)據(jù)直接顯示在頁(yè)面上(比如在做一個(gè)接口測(cè)試的項(xiàng)目,需要將接口返回的結(jié)果直接展示),但是如果直接顯示字符串,不方便查看。需要格式化一下。
解決方案:
其實(shí)JSON.stringify本身就可以將JSON格式化,具體的用法是:
JSON.stringify(res, null, 2); //res是要JSON化的對(duì)象,2是spacing
如果想要效果更好看,還要加上格式化的代碼和樣式:
js代碼:
function syntaxHighlight(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 >樣式代碼:
style pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; } .string { color: green; } .number { color: darkorange; } .boolean { color: blue; } .null { color: magenta; } .key { color: red; } /style html代碼:
pre id= result /pre
調(diào)用代碼:
$( #result ).html(syntaxHighlight(res));
效果:

【相關(guān)推薦】
1. HTML免費(fèi)視頻教程
2. html實(shí)現(xiàn)消息按鈕上的數(shù)量角標(biāo)的實(shí)例詳解
3. Html完成異步上傳文件的Jquery代碼實(shí)例
4. 對(duì)HTTP Headers知識(shí)點(diǎn)的圖文說(shuō)明
5. Html5 datalist標(biāo)簽詳解以及與后臺(tái)數(shù)據(jù)的動(dòng)態(tài)匹配
以上就是html中怎么樣才能讓JSON數(shù)據(jù)顯示的方法介紹的詳細(xì)內(nèi)容,html教程
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注