I am having a table where one column is a JSONB column that has the following payload:
[
{a: "foo", b: "bar"},
{a: "bar", b: "baz"}
]
I want to remove the "b" element for each array item:
SELECT json_build_object(
'id', s.id,
'key', json_build_object(
'key', s.column #- '{1, b}'
)
) FROM table s
This works well but it removes it only from the second element of the array. I would like to remove it for every element of the array (the number of items in the array is not known and cannot be hardcoded.
Is there a way to do that easily?
Thanks!
2
Answers
Unnest the
jsonb
array, subtract the key, and reaggregate:Working fiddle
Try this
jsonb_agg
function by combining it with lateral join.Also replace
your_jsonb_column
with the name of JSONB column that contains the array.Hope it works.