-2

我使用python(django)和extjs4.2,但现在我不知道如何返回extjs treepanel的json格式数据,如下所示:

[{
    "text":"A",
    "id": 1,
    "leaf":false,
    "parentId":0,
    "root":4,
    "children": [{
        "text":"A_1",
        "id":2,
        "leaf":false,
        "parentId":1,
        "root":3,
        "children": [{
            "id":7,
            "leaf":true,
            "parentId":2,
            "root":3,
            "text":"A_1_1",
            "children":[]
        }]
    }]
}]

请帮助我,谢谢。

4

1 回答 1

1

树的结构很容易理解:它是一个嵌套的节点列表,其中每个节点的 children 属性都是它自己的树。可以如下表示:

class Node(object):
    def __init__(self, id, text, root='', parent=None):
        self.text = text
        self.id = id
        self.root = root
        self.parent = parent
        self.children = []

    def append_child(self, node):
        if node not in self.children:
            node.parent = self
            self.children.append(node)

    def remove_child(self, node):
        if node in self.children:
            node.parent = None
            self.children.remove(node)

    def parent_id(self):
        return self.parent.id if self.parent is not None else 0

    def is_leaf(self):
        return len(self.children) == 0

    def to_dict(self):
        children_dict = [child.to_dict() for child in self.children]
        return {
             "id": self.id,
             "root": self.root,
             "text": self.text,
             "leaf": self.is_leaf(),
             "parentId": self.parent_id(),
             "children": children_dict,
         }

    def to_json(self):
        return json.dumps(self.to_dict)
于 2013-08-28T10:30:52.260 回答