I have a hierarchical table in Postgres database, e.g. category. The structure is simple like this:
| id | parent_id | name |
|---|---|---|
| 1 | null | A |
| 2 | null | B |
| 3 | 1 | A1 |
| 4 | 3 | A1a |
| 5 | 3 | A1b |
| 6 | 2 | B1 |
| 7 | 2 | B2 |
What i need to get from this table is recursive deep tree structure like this:
[
{
"id": 1,
"name": "A",
"children": [
{
"id": 3,
"name": "A1",
"children": [
{
"id": 4,
"name": "A1a",
"children": []
},
{
"id": 5,
"name": "A1b",
"children": []
}
]
}
]
},
{
"id": 2,
"name": "B",
"children": [
{
"id": 6,
"name": "B1",
"children": []
},
{
"id": 7,
"name": "B2",
"children": []
}
]
},
]
Is it possible with unknown depth using combination of WITH RECURSIVE and json_build_array() or some other solution?