在html頁面中展示JSON

來源:互聯網
上載者:User

標籤:return   highlight   介面測試   style   ret   lin   height   amp   false   

背景:
有時候我們需要將json資料直接顯示在頁面上(比如在做一個介面測試的項目,需要將介面返回的結果直接展示),但是如果直接顯示字串,不方便查看。需要格式化一下。

解決方案:
其實JSON.stringify本身就可以將JSON格式化,具體的用法是:

JSON.stringify(res, null, 2); //res是要JSON化的對象,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 class="‘ + cls + ‘">‘ + match + ‘</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>

調用代碼:

$(‘#result‘).html(syntaxHighlight(res));

效果:

 

在html頁面中展示JSON

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.