保存为.html 浏览器打开即可,话不多说上代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: 'Courier New', monospace;
background-color: #f5f5f5;
padding: 20px;
}
.string { color: green; }
.number { color: blue; }
.boolean { color: orange; }
.null { color: gray; }
.key { color: brown; }
.bracket { color: black; }
.date { color: purple; }
</style>
<title>JSON Viewer</title>
</head>
<body>
<pre id="json-output"></pre>
<script>
const jsonString = '{"name": "John", "age": 30, "birthdate": "2023-10-27", "isStudent": false, "grades": [90, 85, 78], "info": {"city": "New York", "zip": "10001"}}';
const outputElement = document.getElementById('json-output');
const jsonObject = JSON.parse(jsonString);
function formatJson(obj, indent = 2) {
return JSON.stringify(obj, null, indent)
.replace(/"(\w+)"\s*:/g, '"<span style="color: red;">$1</span>":')
.replace(/(\b(true|false|null)\b)/g, match => `<span style="color: blue;">${match}</span>`) // key 颜色为蓝色
.replace(/: (\d+(\.\d+)?)/g, ': <span style="color: darkorange;">$1</span>') // value 颜色为绿色
.replace(/: ("(\\u[a-zA-Z0-9]{4}|[^"\\])*")/g, ': <span style="color: green;">$1</span>'); // 字符串 value 颜色为红色
}
outputElement.innerHTML = formatJson(jsonObject);
</script>
</body>
</html>