PostgreSQL – Convert Array to JSONB

postgresql

How we can convert postgres array :- ARRAY['{"id": "1"}', '{"id": "2"}'] to JSONB '[{"id": "1"}, {"id": "2"}]'

Best Answer

It appears that you have an array of JSON values, and want to turn that into a single JSONB value which is an array.

You can unnest your array, then cast the elements to JSONB and aggregate that back using jsonb_agg():

select jsonb_agg(j::jsonb)
from unnest(ARRAY['{"id": "1"}', '{"id": "2"}']) as x(j);