1.利用pre标签
body{
padding-top: 20px;
}
#data_info{
width: 100%;
font-size: 16px;
white-space: pre-wrap;
word-wrap: break-word;
}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
var show = document.getElementById('data_info');
var jsondata = {"id": {"first":1, "second":2, "third":3, "fourth": [4, 5, 6, 7], "fifth": 5}, "name": {"ZS": "张三", "LS": "李四"}};
show.innerHTML = pretifyJson(jsondata,true);
/**
* [pretifyJson json格式化打印]
* @param {[type]} json [description]
* @param {Boolean} pretify [description]
* @return {[type]} [description]
*/
function pretifyJson(json, pretify=true) {
if (typeof json !== 'string') {
if(pretify){
json = JSON.stringify(json, undefined, 4);
}else{
json = JSON.stringify(json);
}
}
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
function (match) {
let cls = "";
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = "";
} else {
cls = "";
}
} else if (/true|false/.test(match)) {
cls = "";
} else if (/null/.test(match)) {
cls = "";
}
return cls + match + "";
}
);
}
结果:
2.使用jsonview插件
var jsondata = {"id": {"first":1, "second":2, "third":3, "fourth": [4, 5, 6, 7], "fifth": 5}, "name": {"ZS": "张三", "LS": "李四"}};
$(function() {
/* JSONView第一个参数就是需要转换的json数据 */
$("#data_info").JSONView(jsondata, {collapsed: false, nl2br: true, recursive_collapser: true });
});
结果