1
我有一个数据库表,如下所示。该数据是在树与在Python字典中有一个嵌套列表
CREATE TABLE IF NOT EXISTS DOMAIN_HIERARCHY (
COMPONENT_ID INT NOT NULL ,
LEVEL INT NOT NULL ,
COMPONENT_NAME VARCHAR(127) NOT NULL ,
PARENT INT NOT NULL ,
PRIMARY KEY (COMPONENT_ID)
);
下面的数据是在表中的形式
(1,1,'A',0)
(2,2,'AA',1)
(3,2,'AB',1)
(4,3,'AAA',2)
(5,3,'AAB',2)
(6,3,'ABA',3)
(7,3,'ABB',3)
我必须找回在Python字典
在下面的数据和存储代码
conx = sqlite3.connect('nameofdatabase.db')
curs = conx.cursor()
curs.execute('SELECT COMPONENT_ID, LEVEL, COMPONENT_NAME, PARENT FROM DOMAIN_HIERARCHY')
rows = curs.fetchall()
hrcy = {}
for row in rows:
entry = (row[2], {})
cmap[row[0]] = entry
if row[1] == 1:
hrcy = {entry[0]: entry[1]}
hrcy['status'] = 0
for row in rows:
item = cmap[row[0]]
parent = cmap.get(row[3], None)
if parent:
parent[1][row[2]] = item[1]
parent[1]['status'] = 0
print json.dumps(hrcy, indent = 4)
输出是像
{
"status": 0,
"A": {
"status": 0,
"AA": {
"status": 0,
"AAA": {},
"AAB": {}
},
"AB": {
"status": 0,
"ABA": {},
"ABB": {}
}
}
}
我要像
{
"component": "A",
"status": 0,
"children": [
{
"component": "AA",
"status": 0,
"children": [
{
"component": "AAA",
"status": 0,
"children": []
},
{
"component": "AAB",
"status": 0,
"children": []
}
]
},
{
"component": "AB",
"status": 0,
"children": [
{
"component": "ABA",
"status": 0,
"children": []
},
{
"component": "ABB",
"status": 0,
"children": []
}
]
}
]
}
输出谁能告诉什么样的变化,我应该做什么呢?
不敢相信这简单的小代码解决了我的“无法解决”的问题谢谢你Janne Karela – Praneeth 2013-03-26 08:45:18