I am using postgres and I have multiple entries of jsonb inside an array in a single column called observation. They’re input as
'[{"a": 1}, {"b": 2}, {"c": 0.5}]'::jsonb
.
There are multiple rows, with multiple json elements inside of each one of them. I would like to combine them into one big entry in one row, so that I will just have one observation of one column as a result.
I have tried the following
INSERT INTO data
SELECT jsonb_agg(observation) AS concatenated_json
FROM (
SELECT observation
FROM test
) AS subquery;
But the result I got was an array of arrays. I don’t want to get multiple arrays, just a single one.
3
Answers
You can use
jsonb_object_agg
:See fiddle
This query will, for each row, merge all key-value pairs in the array elements of
observations
into a single object. Then, the merged objects are aggregated into a single array.Use
jsonb_array_elements()
to expand a json array to a set of json values. For example:(3 rows)
will convert into 9 rows of json values:
then we aggregate the json values using
jsonb_agg()
into tabledata
to output one row:You can create a user-defined aggregate which does what you want pretty trivially:
Then use it with GROUP BY, or since you only want one row, use it without GROUP BY:
On the one hand it is nicer than having to unnest the objects and then reassemble them, on the other hand people reading your code might be confused by what looks like it might be a built-in function, but isn’t.