我在数据库中有一组行的结果集,这些行都通过父子关系相互关联
每一行都表示为objectid、id、parent、child、name、level,因此当我从程序中的数据库中读取一个示例时,它看起来是这样的
Organization1
Component1
Department1
Sections1
Sections2
Department2
Sections3
Component2
Department3
Sections4
Sections5
Department4
Sections6
组织有许多部门,部门有许多组件,组件有许多部分
到目前为止,我的代码看起来是这样的,但我需要将其转换为json格式,json格式必须如下所示
for v in result:
level = v[5]
child = v[3]
parent = v[2]
if level == 0:
OrgDic['InstID'] = v[4]
OrgDic['Child'] = v[3]
OrgDic['Parent'] = v[2]
Organizations.append(InstDic)
OrgDic = {}
if level == 1:
ComponentsDic['CollegeID'] = v[4]
ComponentsDic['Child'] = v[3]
ComponentsDic['Parent'] = v[2]
Components.append(CollegeDic)
ComponentsDic = {}
if level == 2:
DepartmentDic['DepartmentID'] = v[4]
DepartmentDic['Child'] = v[3]
DepartmentDic['Parent'] = v[2]
Departments.append(DepartmentDic)
DepartmentDic = {}
if level == 3:
SectionDic['SubjectID'] = v[4]
SectionDic['Child'] = v[3]
SectionDic['Parent'] = v[2]
Sections.append(SubjectDic)
SectionDic = {}
for w in :
print w['Organization']
for x in Components:
if w['Child'] == x['Parent']:
print x['Components']
for y in Departments:
if x['Child'] == y['Parent']:
print y['Deparments']
for z in Sections:
if y['Child'] == z['Parent']:
print z['Sections']
JSON格式
{
"Eff_Date": "08/02/2013",
"Tree":
[
{
"OrganizationID": "Organization1",
"Components":
[
{"ComponentID": "Component1",
"Departments":
[
{"DepartmentID": "Dep1",
"Sections":
[
{"SectionID": "Section1"},
{"SectionID": "Section2"}
]},
{"DepartmentID": "Dep2",
"Sections":
[
{"SectionID": "Section3"}
]}
]}
]
}
基本上,您所要做的就是在第一个代码段之后转储json(假设代码段确实正确地创建了您公开的树,我没有彻底检查它,但它看起来是一致的):
还有塔达!你知道吗
我可以用下面的方法来做
在我的例子中,我的数据是来自一个数据库的结果集,所以我必须按如下方式循环遍历它
相关问题 更多 >
编程相关推荐