I have a table that contains information pertaining to a very large document. The table looks something as follows:
ID | Title | Parent_ID | <other columns>
--------+---------------+---------------+-------------------
0 | Root | null | ...
1 | Introduction | 0 | ...
2 | Glossary | 1 | ...
3 | Audience | 1 | ...
4 | "A" | 2 | ...
5 | "B" | 2 | ...
6 | "C" | 2 | ...
The result JSON should look like (the <other columns> part is omitted for clarity purposes):
{"ID" : 0 ,
"Title" : "Root" ,
"Contents" : [{"ID" : 1 ,
"Title" : "Introduction",
"Contents" : [{"ID" : 2 ,
"Title" : "Glossary" ,
"Contents" : [{"ID" : 4 ,
"Title" : "A" ,
"Contents" : [] },
{"ID" : 5 ,
"Title" : "B" ,
"Contents" : [] },
{"ID" : 6 ,
"Title" : "C" ,
"Contents" : [] }]
},
{"ID" : 3 ,
"Title" : "Audience" ,
"Contents" : []
}
]
},
....
]
}
I do have a simple (recursive) procedure that would handle this, but was hoping there is a simpler way using the JSON capabilities of the DBMS (perhaps using CTE?).