Hướng dẫn python json to collapsible html - python json thành html có thể thu gọn

Tôi cần trợ giúp với việc hiển thị dữ liệu JSON trên một trang như Danh sách có thể mở rộng/có thể thu gọn.

Đây là một JSON hợp lệ, tôi đã chuyển đổi từ XML với Python:

Dữ liệu JSON

Và để hiển thị nó, tôi đang sử dụng điều này:

<!DOCTYPE HTML>
<head>
    <title>JSON Tree View</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js" type="text/javascript"></script>

</head>
<script>
function json_tree(object){
        var json="<ul>";
        for(prop in object){
            var value = object[prop];
            switch (typeof(value)){
                case "object":
                    var token = Math.random().toString(36).substr(2,16);
                    json += "<li><a class='label' href='#"+token+"' data-toggle='collapse'>"+prop+"="+value+"</a><div id='"+token+"' class='collapse'>"+json_tree(value)+"</div></li>";
                break;
                default:
                json += "<li>"+prop+"="+value+"</li>";
            }
        }
        return json+"</ul>";
}
</script>
<body style="margin: 40px;">
<h3>Paste JSON Into The Textarea Below and Click 'Build Tree'</h3>

<textarea id="json" style="width: 100%;min-height:300px;">

</textarea>
<button onclick="$('#output').html(json_tree(JSON.parse($('#json').val())));">Build Tree</button>
<div id="output">

</div>
</body>
</html>

Đây là những gì tôi nhận được:

Hình ảnh

Tôi cần trợ giúp "Filltering" (hoặc hợp nhất với nút trên) Các "0" và "1", và cả - làm thế nào để chỉ hiển thị các giá trị của các thuộc tính mà không có tên (hoặc nếu bạn có ý tưởng tốt hơn làm thế nào danh sách)?

Hướng dẫn python json to collapsible html - python json thành html có thể thu gọn

Hỏi ngày 13 tháng 9 năm 2015 lúc 12:11Sep 13, 2015 at 12:11

Hướng dẫn python json to collapsible html - python json thành html có thể thu gọn

3

Chế độ xem cây đẹp, nhỏ gọn, có thể thu gọngood-looking, compact, collapsible tree view

PGRABOVETS 'json-view là sạch sẽ và được thiết kế tốt.

Kiểm tra bản demo

Đã trả lời ngày 2 tháng 5 năm 2020 lúc 3:56May 2, 2020 at 3:56

Hướng dẫn python json to collapsible html - python json thành html có thể thu gọn

InigoinigoInigo

9.0044 Huy hiệu vàng32 Huy hiệu bạc62 Huy hiệu Đồng4 gold badges32 silver badges62 bronze badges

Nếu bạn có thể xem xét sử dụng các thư viện JS, hãy xem xét sử dụng JSON Formatter hoặc Render JSON. Cả hai thư viện này đều cung cấp các tùy chọn cấu hình như chủ đề, độ sâu tối đa và sắp xếp. Để hiển thị chuỗi JSON đơn giản ở dạng thu gọn bằng cách sử dụng Render JSON, bạn có thể sử dụng

<script>
    document.getElementById("test").appendChild(
        renderjson({ hello: [1,2,3,4], there: { a:1, b:2, c:["hello", null] } })
    );
</script>

Đã trả lời ngày 26 tháng 7 năm 2017 lúc 8:53Jul 26, 2017 at 8:53

Bilal Akbarbilal AkbarBilal Akbar

4.3811 Huy hiệu vàng18 Huy hiệu bạc29 Huy hiệu đồng1 gold badge18 silver badges29 bronze badges

1

Một số liên kết đến các câu hỏi không còn có thể truy cập được. Tôi cho rằng bạn đang tìm cách làm cho một chế độ xem JSON có thể thu gọn.


TL;DR

Bạn có thể nhảy vào toàn bộ mã.Full code.

Mã này rất ngắn (200 dòng, bao gồm JSDOC, Nhận xét, Mã kiểm tra.)

Truyền cảm hứng cho bạn về cách giải quyết vấn đề.

Câu hỏi này trong một số kỹ năng rất giống như làm thế nào để làm cho bảng nội dung. (TOC)

  1. Trước hết, dữ liệu JSON giống như một đối tượng. Tất cả những gì chúng ta cần làm là thêm một số thuộc tính (khóa, độ sâu, trẻ em, ...) cho mỗi mục.add some more attributes (key, depth, children, ...) for each item.

  2. Một khi những hành động này được thực hiện, tất cả còn lại là kết xuất, và đây là mã giả để kết xuất.render, and here is the pseudo-code for rendering.

    render(node) {
      const divFlag = document.createRange().createContextualFragment(`<div style="margin-left:${node.depth * 18}px"></div>`)
      const divElem = divFlag.querySelector("div")
      const spanFlag = document.createRange().createContextualFragment(
        `<span class="ms-2">${node.key} : ${node.value}</span>`
      )
      node.children.forEach(subNode => {
        const subElem = render(subNode)
        spanFlag.append(subElem)
      })
      divElem.append(spanFlag)
      return divElem
    }
    

Mã đầy đủ

Cả CSS là không cần thiết.

  • Bootstrap: MS-2 (Bắt đầu lề)
  • Fontawesome: FA-caret-right, fa-caret-down Nếu bạn không muốn sử dụng nó, bạn có thể sử dụng ▸ (25b8) ▶ (25b6) ▾ (25be) ▼ (25BC)

<link href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossOrigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"
      integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="
      crossOrigin="anonymous" referrerpolicy="no-referrer"/>

<script type="module">
  // 👇 main script {Node, Tree, JsonView}
  class Node {
    /**
     * @description Add more attributes to the item.
     * @param {*} item
     * @param {*} key
     * @param {Node} parent
     * */
    constructor(item, key, parent) {
      this.key = key

      /** @param {string} */
      this.type = Array.isArray(item) ? "array" : typeof item

      /** @param {Number} */
      this.depth = parent ? parent.depth + 1 : 0
      this.value = item
      this.parent = parent

      /** @param {[Node]} */
      this.children = []
    }
  }

  class Tree {
    /**
     * @description Given the root node, it will complete the children of it.
     * @param {Node} rootNode
     */
    constructor(rootNode) {
      this.root = rootNode

      const obj = this.root.value
      if (!(obj instanceof Object)) { // Array is an Object too.
        return
      }
      Object.keys(obj).forEach(keyOrIdx => {
        const value = obj[keyOrIdx]
        const subNode = new Node(value, keyOrIdx, rootNode)
        const subTree = new Tree(subNode)
        rootNode.children.push(subTree.root)
      })
    }

    /**
     * @param {string | Object} jsonData
     * @return {Tree}
     */
    static CreateTree(jsonData) {
      jsonData = typeof jsonData === "string" ? JSON.parse(jsonData) : jsonData
      const rootNode = new Node(jsonData, "root", null)
      return new Tree(rootNode)
    }
  }

  class JsonView {
    static DefaultColorMap = {
      text: {
        string: "green",
        number: "#f9ae58",
        boolean: "#ca4ff8",
        array: "black",
        object: "black",
      },
      bg: {
        object: undefined,
        // ... You can add more by yourself. They are like the text as above.
      }
    }

    static NewConfig() {
      return JSON.parse(JSON.stringify(JsonView.DefaultColorMap))
    }

    static SEPARATOR = " : "

    /** @type {Tree} */
    #tree

    /**
     * @param {Tree} tree
     * */
    constructor(tree) {
      this.#tree = tree
    }

    /**
     * @param {Node} node
     * @param {Object} colorMap
     */
    #render(node, colorMap = JsonView.DefaultColorMap) {
      /**
       * @param {Node} node
       * */
      const getValue = (node) => {
        const typeName = node.type
        switch (typeName) {
          case "object":
            return `object {${Object.keys(node.value).length}}`
          case "array":
            return `array [${Object.keys(node.value).length}]`
          default:
            return node.value
        }
      }

      const arrowIcon = ["object", "array"].includes(node.type) ? `<i class="fas fa-caret-down"></i>` : ""
      const divFlag = document.createRange().createContextualFragment(`<div style="margin-left:${node.depth * 18}px">${arrowIcon}</div>`)
      const divElem = divFlag.querySelector("div")

      const textColor = colorMap.text[node.type] !== undefined ? `color:${colorMap.text[node.type]}` : ""
      const bgColor = colorMap.bg[node.type] !== undefined ? `background-color:${colorMap.bg[node.type]}` : ""
      const valueStyle = (textColor + bgColor).length > 0 ? `style=${[textColor, bgColor].join(";")}` : ""

      const keyName = node.depth !== 0 ? node.key + JsonView.SEPARATOR : "" // depth = 0 its key is "root" which is created by the system, so ignore it.
      const spanFlag = document.createRange().createContextualFragment(
        `<span class="ms-2">${keyName}<span ${valueStyle}>${getValue(node)}</span></span>`
      )

      const isCollapsible = ["object", "array"].includes(node.type)

      node.children.forEach(subNode => {
        const subElem = this.#render(subNode, colorMap)

        if (isCollapsible) {
          divFlag.querySelector(`i`).addEventListener("click", (e) => {
            e.stopPropagation()
            subElem.dataset.toggle = subElem.dataset.toggle === undefined ? "none" :
              subElem.dataset.toggle === "none" ? "" : "none"

            e.target.className = subElem.dataset.toggle === "none" ? "fas fa-caret-right" : "fas fa-caret-down" // Change the icon to ▶ or ▼

            subElem.querySelectorAll(`*`).forEach(e => e.style.display = subElem.dataset.toggle)
          })
        }

        spanFlag.append(subElem)
      })
      divElem.append(spanFlag)
      return divElem
    }

    /**
     * @param {Element} targetElem
     * @param {?Object} colorMap
     */
    render(targetElem, colorMap = JsonView.DefaultColorMap) {
      targetElem.append(this.#render(this.#tree.root, colorMap))
    }
  }

  // 👇 Below is Test
  function main(outputElem) {
    const testObj = {
      db: {
        port: 1234,
        name: "My db",
        tables: [
          {id: 1, name: "table 1"},
          {id: 2, name: "table 2"},
        ],
      },
      options: {
        debug: false,
        ui: true,
      },
      person: [
        "Foo", 
        "Bar"
      ]
    }
    const tree = Tree.CreateTree(testObj)
    const jsonView = new JsonView(tree)
    jsonView.render(outputElem)
    /* If you want to set the color by yourself, you can try as below
    const config = JsonView.NewConfig()
    config.bg.object = "red"
    jsonView.render(outputElem, config)
     */
  }

  (() => {
    window.onload = () => {
      main(document.body)
    }
  })()
</script>

Vanilla JavaScript

Đã trả lời ngày 16 tháng 10 năm 2021 lúc 12:37Oct 16, 2021 at 12:37

Hướng dẫn python json to collapsible html - python json thành html có thể thu gọn

CarsonCarsonCarson

4.6502 Huy hiệu vàng29 Huy hiệu bạc40 Huy hiệu đồng2 gold badges29 silver badges40 bronze badges

1