I have data from a table in Postgres that I need to be returned in Json format with its children properly ordered. So far, I haven't found a solution to achieve this. Is there a way in PostgreSQL to order the parent modules along with their child modules? Here is an example:
[
{
"id_module": 1,
"id_parent_module": null,
"module_code": "001.",
"name_module": "Atoridad Fiscal",
"desc_module": "Atoridad Fiscal",
"children": [{
"id_module": 2,
"id_parent_module": 1,
"module_code": "001.002",
"name_module": "Recibidos",
"desc_module": "Recibidos"
},
{
"id_module": 3,
"id_parent_module": 1,
"module_code": "001.003.",
"name_module": "Enviados",
"desc_module": "Enviados"
},
{
"id_module": 4,
"id_parent_module": 1,
"module_code": "001.004.",
"name_module": "Archivados",
"desc_module": "Archivados"
}]
},
{
"id_module": 5,
"id_parent_module": null,
"module_code": "005.",
"name_module": "Configuraciones",
"desc_module": "Configuraciones",
"children": [{
"id_module": 14,
"id_parent_module": 5,
"module_code": "005.014.",
"name_module": "Medios Contacto",
"desc_module": "Medios Contacto"
}]
},
{
"id_module": 6,
"id_parent_module": null,
"module_code": "006.",
"name_module": "Mensajes",
"desc_module": "Bandeja del contribuyente",
"children": [{
"id_module": 7,
"id_parent_module": 6,
"module_code": "006.007.",
"name_module": "Recibidos",
"desc_module": "Recibidos"
},
{
"id_module": 8,
"id_parent_module": 6,
"module_code": "006.008.",
"name_module": "Enviados",
"desc_module": "Enviados"
},
{
"id_module": 22,
"id_parent_module": 6,
"module_code": "006.022.",
"name_module": "Buscador de Mensajes",
"desc_module": "Buscador de Mensajes"
}]
}
]
I have attempted using
SELECT array_to_json(array_agg(row_to_json(alias))) FROM (select * from my table ) alias
but it only returns the JSON without organizing the data with its children.