需求:类似于vscode代码颜色处理,在页面中,美化展示一段JSON串。
先来看下效果,此例只针对基本数据类型(函数字符串无法显示)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>
</head>
<body>
<pre id="box"></pre>
<script>
const obj = {
name:'Tom',
age:25,
alive:true,
array:[true,'javascript',1024],
others:{
firend:'Jerry',
age:24,
alive:false,
},
}
let box = document.getElementById('box')
box.innerHTML = JSON.stringify(obj,null, '\t')
.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>';
});
</script>
</body>
</html>