2013-08-28 38 views
-2

我用extjs4.2蟒蛇(Django的)的ExtJS的JSON數據,但現在我不知道怎麼回的ExtJS的JSON格式的數據如下TreePanel中,如:使用Python返回TreePanel中

[{ 
    "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":[] 
     }] 
    }] 
}] 

請幫助我,謝謝。

+0

你有什麼?你有什麼嘗試? – Fabian

+0

你能更具體嗎?你從哪裏得到這些數據?你有django中的樹對象,它可以在序列化時給你這些數據嗎? –

+0

我從一個java + extjs4項目的例子中獲取數據,但我使用python,所以... – user2724512

回答

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) 
+0

謝謝,我會試一試。 – user2724512