[英]Converting postgresql database table into json tree python
I have a database table with recursive relationship: 我有一个具有递归关系的数据库表:
I need to convert the above data into JSON format so it could fit into ng2-tree: 我需要将上述数据转换为JSON格式,以便它适合ng2-tree:
{
value: 1,
data: "d1"
children: [
{
value: '2',
data: "d2"
children: [
{value: 3,
data: "d3",
children: [
value: 4,
data: "d4",
children : []
]},
{value: 6, data: "d6", children: []}
]
},
{
value: '5',
data: "d5"
children: [
]
}
]
}
I have tried various implementations including creating a tree using edges from above table and then making the json structure using recursion, but i am having problem with adding the data value in the resulting json. 我尝试了各种实现,包括使用上表中的边创建树,然后使用递归制作json结构,但是我在将数据值添加到结果json中时遇到问题。
I am using python2 to write the following code, any help is appreciated. 我正在使用python2编写以下代码,感谢您的帮助。
You can use recursion: 您可以使用递归:
import sqlite3
data = list(sqlite3.connect('filename.db').cursor().execute("SELECT * FROM tablename"))
#[[1, 'None', 'd1'], [2, 1, 'd2'], [3, 2, 'd3'], [4, 3, 'd4'], [5, 1, 'd5'], [6, 2, 'd6']]
def group_vals(_start):
return [{'value':a, 'data':c, 'children':group_vals(a)} for a, b, c in data if b == _start]
[[val, _data]] = [[a, c] for a, b, c in data if b == 'None']
new_result = {'value':val, 'data':_data, 'children':group_vals(val)}
Output: 输出:
{
"value": 1,
"data": "d1",
"children": [
{
"value": 2,
"data": "d2",
"children": [
{
"value": 3,
"data": "d3",
"children": [
{
"value": 4,
"data": "d4",
"children": []
}
]
},
{
"value": 6,
"data": "d6",
"children": []
}
]
},
{
"value": 5,
"data": "d5",
"children": []
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.