我有一个如下的数据库表。数据采用树的形式
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": []
}
]
}
]
}
谁能告诉我应该做些什么改变?