对查询到的json格式数据,页面要展示成JSON形式方便查看,不想引入json插件,使用一些方法:
首先定义格式化函数:
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; } /*null值的样式*/
.key { color: red; } /*key值的样式*/
</style>
定义输出html:
<pre id="result"></pre>
最后输出:
$('#result').html(syntaxHighlight(data));
效果图: