在html中顯示JSON數(shù)據(jù)的方法
發(fā)布時(shí)間:2017-05-10 14:55:55 作者:佚名
我要評論

在項(xiàng)目中我們需要將json數(shù)據(jù)直接顯示在頁面上,但是如果直接顯示字符串很不方便查看,下面小編給大家?guī)砹薶tml中顯示JSON數(shù)據(jù)的方法,需要的的朋友參考下吧
背景:
有時(shí)候我們需要將json數(shù)據(jù)直接顯示在頁面上(比如在做一個接口測試的項(xiàng)目,需要將接口返回的結(jié)果直接展示),但是如果直接顯示字符串,不方便查看。需要格式化一下。
解決方案:
其實(shí)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>
調(diào)用代碼:
$('#result').html(syntaxHighlight(res));
效果:
以上所述是小編給大家介紹的在html中顯示JSON數(shù)據(jù)的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
- 這篇文章主要介紹了html格式化json的實(shí)例代碼,需要的朋友可以參考下2017-05-22
- 這篇文章主要介紹了舉例詳解HTML5中使用JSON格式提交表單,包括多重?cái)?shù)組嵌套等方法的使用演示,需要的朋友可以參考下2015-06-16
- 本篇文章主要介紹了html格式化輸出JSON示例(測試接口) ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-14