在线 JSON 格式化工具 - 可折叠树形结构展示
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>在线 JSON 格式化工具</title>
<style>
body {
font-family: Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
background-color: #f5f5f5;
margin: 0;
padding: 0;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
textarea {
width: 100%;
min-height: 200px;
padding: 10px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #fff;
resize: none;
}
.result {
margin-top: 20px;
padding: 10px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #fff;
}
.property {
margin-left: 20px;
padding-left: 20px;
position: relative;
border-left: 1px solid #ccc;
list-style: none;
}
.property:before {
content: '';
position: absolute;
left: -10px;
top: 5px;
width: 6px;
height: 6px;
border-radius: 50%;
background-color: #ccc;
}
.property.open:before {
background-color: #009688;
}
.property > span {
cursor: pointer;
}
.property > .key {
font-weight: bold;
}
.property > .value {
color: #666;
}
.property > ul {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div class='container'>
<h1>在线 JSON 格式化工具</h1>
<p>输入要格式化的 JSON:</p>
<textarea id='input'></textarea>
<button onclick='format()'>格式化</button>
<div class='result' id='result'></div>
</div>
<script>
function format() {
var input = document.getElementById('input').value;
var json;
try {
json = JSON.parse(input);
} catch (e) {
alert('输入的不是有效的 JSON 格式!');
return;
}
var result = document.getElementById('result');
result.innerHTML = '';
var ul = document.createElement('ul');
render(json, ul);
result.appendChild(ul);
}
<pre><code> function render(obj, ul) {
for (var key in obj) {
var li = document.createElement('li');
var span = document.createElement('span');
var value = obj[key];
span.className = 'key';
span.innerText = key + ': '; //key+ ':' +value; // 这样显示 key:value 格式的,方便 测试
if (typeof value === 'object') {
if (Array.isArray(value)) {
span.innerText += '[' + value.length + ']';
} else {
span.innerText += '{...}';
}
span.addEventListener('click', function() {
var property = this.parentNode;
if (property.classList.contains('open')) {
property.classList.remove('open');
var subUl = property.querySelector('ul');
if (subUl) {
property.removeChild(subUl);
}
} else {
property.classList.add('open');
var subUl = document.createElement('ul');
subUl.style.marginLeft = '20px';
render(value, subUl);
property.appendChild(subUl);
}
});
} else if (typeof value === 'string') {
span.innerText += ''' + value + '''; // 原来的双引号改成了单引号
span.className = 'key value';
} else {
span.innerText += value;
span.className = 'key value';
}
li.appendChild(span);
ul.appendChild(li);
}
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/mNE5 著作权归作者所有。请勿转载和采集!