I have a rows that have json formatted as
[{"FIRST": {"0": 1580, "1": 1745, "2": 2050, "3": 2395}}, {"SECOND": {"1": 1895, "2": 2431}}]
Because of the way the SQL was written there is only ever one toplevel key. I don't want to hardcode anything. I've tried a few solutions and they've led to me dropping values. I'm looking for a way to do this in pure Postgres that these objects get flattened and the array gets removed.
Expected output:
{"FIRST": {"0": 1580, "1": 1745, "2": 2050, "3": 2395}, "SECOND": {"1": 1895, "2": 2431}}
Anyone have an idea how I could go about doing this?
This should be pretty simple with
jsonb_array_elements,jsonb_eachandjsonb_object_agg:(online demo)
You'll want to either
GROUP BYsome row identifier or select only a single row with aWHEREclause. Alternatively use a subquery: