将Postgresql数据库表转换为JSON树python

时间:2018-11-27 14:22:37

标签: python postgresql data-structures tree

我有一个具有递归关系的数据库表:

enter image description here

我需要将上述数据转换为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: [
        ]
      }
    ]
  }

我尝试了各种实现方式,包括使用上表中的边创建树,然后使用递归创建json结构,但是我在将数据值添加到结果json中时遇到问题。

我正在使用python2编写以下代码,感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用递归:

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)}

输出:

{
   "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": []
     }
  ] 
}