我如何转 `[(1, 'item1'),(2, "item2"),(2, "item3"),(3, "item4"),(2, "item5")]` 进入 JSON 树和 python 中的 HTML 树?

How do i turn `[(1, 'item1'),(2, "item2"),(2, "item3"),(3, "item4"),(2, "item5")]` into a JSON tree and HTML tree in python?

我已经在这个问题上反复讨论了几个小时,但我似乎做不到。

我一直在尝试将问题分解为 if 语句,例如 if previous number < number then create a child group and then go through it 但我一直在想办法解决问题树很容易。我本以为会有 json 的工具可以让我这样做,但我似乎找不到任何工具。

我想将像 [(1, 'item1'),(2, "item2"),(2, "item3"),(3, "item4"),(2, "item5")] 这样的元组列表变成 JSON 和 HTML。 我认为我没有清楚地解释树的格式,所以我会更详细地介绍。 每个数字代表节点的级别,并且是有序的,所以它应该是一个元组。 它显示为 print '\t' * indent

Item1
    Item2
    Item3
        Item4
    Item5

每当数字递增时,所有递增的项目都是前一个数字的子项。

Item1
    Child of Item1
    Child Item2
        Child of item2
        Child Item3
            Child of Item 3
        Child of item2
    Child of Item 1

当你把这个有序列表放在一起时,你可以把它变成一个 Json 树 像下面这样,这就是我正在努力的方向。

{
 "name": "item1",
 "children": [
  {"name": "item2"}
  {
   "name": "item3",
   "children": [
     {"name": "item4"}
   ]
  }
  {"name": "item5"}
 ]
}

和HTML树

<div class="list">
    <ul>
        <li><span>item</span>
            <ul>
                <li>item2</li>
                <li><span>item3</span>
                    <ul>
                        <li>item4</li>
                    </ul>
                </li>
                <li>item5</li>
            </ul>
        </li>
    </ul>
</div>

它需要取 x 件物品。

下面的代码是相当递归的,但是给你想要的结果 JSON。如果这是可以接受的,我将考虑生成类似的 HTML.

data = [(1, 'item1'), (2, "item2"), (2, "item3"), (3, "item4"), (2, "item5")]

import json


class Entity(object):
    def __init__(self, name=None, parent=None):
        self.name = name
        self.parent = parent
        self.level = parent.level + 1 if parent else 0
        self.children = []

    def to_json_obj(self):
        if len(self.children):
            return {'name': self.name, 'children': [child.to_json_obj() for child in self.children]}
        else:
            return {'name': self.name}


def data_to_json(data):
    tree = Entity()
    current = tree
    for item in data:
        if item[0] > current.level:
            pass
        else:
            while True:
                current = current.parent
                if current.level == item[0] - 1:
                    break
        new = Entity(item[1], current)
        current.children.append(new)
        current = new
    return json.dumps(tree.to_json_obj()["children"][0], indent=2)

print data_to_json(data)

给出输出

{
  "name": "item1",
  "children": [
    {
      "name": "item2"
    },
    {
      "name": "item3",
      "children": [
        {
          "name": "item4"
        }
      ]
    },
    {
      "name": "item5"
    }
  ]
}