2011-09-22 103 views
0

我使用的SQLAlchemy存儲在一個數據庫中的二叉樹數據:編碼的二進制樹JSON

class Distributor(Base): 
    __tablename__ = "distributors" 

    id = Column(Integer, primary_key=True) 
    upline_id = Column(Integer, ForeignKey('distributors.id')) 
    left_id = Column(Integer, ForeignKey('distributors.id')) 
    right_id = Column(Integer, ForeignKey('distributors.id')) 

我怎麼能產生像上面列出的JSON「樹」格式的數據:

{'id':1,children:[{'id':2, children:[{'id':3, 'id':4}]}]}

+0

對於您提出的問題,有一個相當簡單的解決方案,但在此之前,您究竟在做什麼? 「分銷商」的左右兒童究竟是什麼?你在這裏試圖解決什麼問題?想要或需要一個用每個頂點的行表示並固定的圖表是不常見的,將邊緣命名爲列。 – SingleNegationElimination

回答

0

我猜你想要以JSON格式存儲數據?或者你是否試圖從標準關係數據構建JSON?

如果是前者,你爲什麼不只是創建類似的條目:

{id: XX, parentId: XX, left: XX, right: XX, value: "foo"} 

對於每一個節點,然後從項手動重建樹?從頭開始(parentId == null),然後組裝分支。

如果數據庫中有多個樹,您也可以爲樹本身添加一個附加標識符。然後,您只需查詢treeId爲XXX的位置,然後從條目構造樹。

0

我毫不猶豫地提供這個答案,因爲我不確定我是否真的明白你想解決的問題(二叉樹,JSON,sqlalchemy,這些都不是問題)。

你可以用這種結構做什麼,就是遍歷每一行,隨着你的走向添加邊。您將從基本上是對象緩存的內容開始;這將最終成爲你需要的樹。

import collections 
idmap = collections.defaultdict(dict) 
for distributor in session.query(Distributor): 
    dist_dict = idmap[distributor.id] 
    dist_dict['id'] = distributor.id 
    dist_dict.setdefault('children', []) 
    if distributor.left_id: 
     dist_dict.['children'].append(idmap[distributor.left_id]) 
    if distributor.right_id: 
     dist_dict.['children'].append(idmap[distributor.right_id]) 

所以我們有一個可以代表樹的大量鏈接的字典。不過,我們不知道哪一個是根源,

root_dist = session.query(Distributor).filter(Distributor.upline_id == None).one() 
json_data = json.dumps(idmap[root_dist.id])