在线 JSON 格式化工具 - 可视化树形结构展示
<!DOCTYPE html>
<html>
<head>
<title>在线 JSON 格式化工具</title>
<style>
ul {
list-style: none;
padding-left: 20px;
}
li {
cursor: pointer;
}
li:hover {
background-color: #f2f2f2;
}
.property {
font-weight: bold;
}
.collapsed {
display: none;
}
</style>
</head>
<body>
<h1>在线 JSON 格式化工具</h1>
<label for="json-input">输入 JSON:</label>
<input type="text" id="json-input">
<button onclick="formatJson()">格式化</button>
<div id="json-tree"></div>
<pre><code><script>
function formatJson() {
const jsonInput = document.getElementById("json-input").value;
const jsonObj = JSON.parse(jsonInput);
const jsonTree = document.getElementById("json-tree");
jsonTree.innerHTML = "";
jsonTree.appendChild(renderJson(jsonObj));
}
function renderJson(obj) {
const ul = document.createElement("ul");
for (let key in obj) {
const li = document.createElement("li");
li.innerHTML = `<span class='property'>${key}: </span>`;
const value = obj[key];
if (typeof value === "object") {
li.classList.add("collapsed");
li.onclick = function() {
this.classList.toggle("collapsed");
};
li.appendChild(renderJson(value));
} else {
li.innerHTML += value;
}
ul.appendChild(li);
}
return ul;
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/mNHL 著作权归作者所有。请勿转载和采集!