PostgreSQL Ltree至JSON

时间:2019-04-06 14:32:34

标签: json postgresql ltree

我一直在尝试PostgreSQL的Ltree扩展。我想用它来存储分层的待办事项列表数据(即带有子列表的列表)。它运行良好,但是花了相当长的时间后,我仍然找不到一种以分层JSON格式从数据库检索信息的好方法。这是我要实现的示例:

 id |        content         | position | parent_id | parent_path 
----+------------------------+-----------+----------+-------------+
  1 | Fix lecture notes.     |        1 |           | root
  2 | Sort out red folder.   |        1 |         1 | root.1
  3 | Order files.           |        1 |         2 | root.1.2
  4 | Label topics.          |        2 |         2 | root.1.2
  5 | Sort out blue folder.  |        2 |         1 | root.1
  6 | Look for jobs.         |        2 |           | root

从此,到下面的json输出:

[
   {
      "id":1,
      "content":"Fix lecture notes.",
      "position":1,
      "parent_id":null,
      "parent_path":"root",
      "children":[
         {
            "id":2,
            "content":"Sort out red folder.",
            "position":1,
            "parent_id":1,
            "parent_path":"root.1",
            "children":[
               {
                  "id":3,
                  "content":"Order files.",
                  "position":1,
                  "parent_id":2,
                  "parent_path":"root.1.2",
                  "children":[]
               },
               {
                  "id":4,
                  "content":"Label topics.",
                  "position":2,
                  "parent_id":2,
                  "parent_path":"root.1.2",
                  "children":[]
               }
            ]
         },
         {
            "id":2,
            "content":"Sort out blue folder.",
            "position":2,
            "parent_id":1,
            "parent_path":"root.1",
            "children":[]
         }
      ]
   },
   {
      "id":1,
      "content":"Look for jobs.",
      "position":1,
      "parent_id":null,
      "parent_path":"root",
      "children":[]
   }
]

是否可以使用Python服务器端完成此操作的整洁方法?真的在寻找想法!

0 个答案:

没有答案