I have a simple table like this:
Key_1 | Key_2 | Value
Rows have multiple combinations of key_1 and key_2.
I want to put rows from this table into a JSON structure like this:
{
"myJSON": {
"key_1": {
"key_2": value,
"key_2": value
}
"key_1": {
"key_2": value,
"key_2": value
}
}
I am able to get the output into rows using this query:
SELECT
key_1,
jsonb_object_agg(key_2,value)
FROM table
GROUP BY key_1
ORDER BY key_1;
This produces output like this:
key_1 | {"key_2":value, "key_2": value}
key_1 | {"key_2":value, "key_2": value}
However I can't work out the last step to get those returned rows into a JSON object structure as per above. I can't use another aggregation function because it complains about nesting.
Is there a way I can do it, or is it something I'll have to do with the result set outside of the database?