html中格式化显示json
JSON.stringify可以将JSON格式化,用法如下
JSON.stringify(json, null, 4); //res是要JSON化的对象,2是spacing
如果需要对key和value加上颜色,还需要以下代码
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>';
});
}css样式如下
<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="json"> </pre>
$('#json').html(syntaxHighlight(json)); 相关推荐
haohong 2020-04-09
玫瑰小妖 2019-12-31
qsdnet我想学编程 2019-12-27
WebVincent 2019-08-02
fengent 2018-11-28
zljiaa 2019-06-28
yesbuy00 2018-01-29
codingker 2017-12-07
wangnan0 2016-10-18
Dr凉 2016-07-13
ReunionIsland 2016-03-18
hong 2013-04-12
htmlgood 2011-04-13
lanyanai 2013-10-24