<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>在线 JSON 格式化工具</title>
    <style>
      .tree { margin-left: 20px; }
      .tree li { list-style-type: none; }
      .tree li:before {
        content: "";
        display: inline-block;
        width: 0;
        height: 0;
        margin-left: -20px;
        margin-right: 10px;
        vertical-align: middle;
        border-top: 5px solid transparent;
        border-bottom: 5px solid transparent;
        border-left: 10px solid black;
      }
    </style>
  </head>
  <body>
    <h1>在线 JSON 格式化工具</h1>
    <label for="json-input">输入 JSON:</label>
    <textarea id="json-input" rows="10" cols="50"></textarea>
    <br>
    <button id="format-button">格式化</button>
    <br>
    <div id="json-tree"></div>
    <script>
      function createTree(obj, parent) {
        const ul = document.createElement("ul");
        parent.appendChild(ul);
        for (const key in obj) {
          const value = obj[key];
          const li = document.createElement("li");
          ul.appendChild(li);
          if (typeof value === 'object') {
            const span = document.createElement("span");
            span.textContent = key;
            li.appendChild(span);
            if (Array.isArray(value)) {
              span.textContent += ' []';
            } else {
              span.textContent += ' {}';
            }
            span.style.cursor = 'pointer';
            span.onclick = function() {
              if (ul.style.display === 'none') {
                ul.style.display = 'block';
              } else {
                ul.style.display = 'none';
              }
            };
            createTree(value, li);
          } else {
            li.textContent = `${key}: ${value}`;
          }
        }
      }
<pre><code>  document.getElementById(&quot;format-button&quot;).onclick = function() {
    const jsonInput = document.getElementById(&quot;json-input&quot;);
    const jsonString = jsonInput.value;
    try {
      const jsonObj = JSON.parse(jsonString);
      const jsonTree = document.getElementById(&quot;json-tree&quot;);
      jsonTree.innerHTML = &quot;&quot;;
      createTree(jsonObj, jsonTree);
    } catch (error) {
      alert(&quot;输入的不是合法的 JSON!&quot;);
    }
  };
&lt;/script&gt;
</code></pre>
  </body>
</html>
在线 JSON 格式化工具 - 轻松将 JSON 数据转化为树形结构

原文地址: https://www.cveoy.top/t/topic/mNGM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录