Python中文
首页
教程
问答
标签
搜索
登录
注册
使用属于某个paren的数组格式化为json
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我在数据库中有一组行的结果集,这些行都通过父子关系相互关联</p> <p>每一行都表示为objectid、id、parent、child、name、level,因此当我从程序中的数据库中读取一个示例时,它看起来是这样的</p> <pre><code>Organization1 Component1 Department1 Sections1 Sections2 Department2 Sections3 Component2 Department3 Sections4 Sections5 Department4 Sections6 </code></pre> <p>组织有许多部门,部门有许多组件,组件有许多部分</p> <p>到目前为止,我的代码看起来是这样的,但我需要将其转换为json格式,json格式必须如下所示</p> <pre><code> 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'] </code></pre> <p>JSON格式</p> <pre><code>{ "Eff_Date": "08/02/2013", "Tree": [ { "OrganizationID": "Organization1", "Components": [ {"ComponentID": "Component1", "Departments": [ {"DepartmentID": "Dep1", "Sections": [ {"SectionID": "Section1"}, {"SectionID": "Section2"} ]}, {"DepartmentID": "Dep2", "Sections": [ {"SectionID": "Section3"} ]} ]} ] } </code></pre>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>基本上,您所要做的就是在第一个代码段之后转储json(假设代码段确实正确地创建了您公开的树,我没有彻底检查它,但它看起来是一致的):</p> <pre><code>import json print json.dumps({"Eff_Date": "08/02/2013", "Tree":Organizations}) </code></pre> <p>还有塔达!你知道吗</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
无法使用Django/mongoengine连接到MongoDB(身份验证失败)
4 回答
无法使用Django\u mssql\u后端迁移到外部hos
7 回答
无法使用Django&Python3.4连接到MySql
4 回答
无法使用Django+nginx上载媒体文件
10 回答
无法使用Django1.6导入名称模式
1 回答
无法使用Django1.7和mongodb登录管理站点
3 回答
无法使用Djangoadmin创建项目,进程使用了错误的路径,因为我事先安装了错误的Python
5 回答
无法使用Djangockedi验证CBV中的字段
5 回答
无法使用Djangocketditor上载图像(错误400)
10 回答
无法使用Djangocron进行函数调用
10 回答
无法使用Djangofiler djang上载文件
4 回答
无法使用Djangokronos
5 回答
无法使用Djangomssql provid
6 回答
无法使用Djangomssql连接到带有Django 1.11的MS SQL Server 2016
3 回答
无法使用Djangomssq迁移Django数据库
6 回答
无法使用Djangonox创建用户
10 回答
无法使用Djangopyodb从Django查询SQL Server
6 回答
无法使用Djangopython3ldap连接到ldap
2 回答
无法使用Djangoredis连接到redis
7 回答
无法使用Django中的FK创建新表
8 回答