4

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

priyavrat narula
  • 43
  • 1
  • 1
  • 3

2 Answers2

14

The array_to_json function with a cast to jsonb accomplishes this.

Example: select array_to_json(ARRAY['{"id": "1"}', '{"id": "2"}'])::jsonb;

Mark Douglas
  • 141
  • 1
  • 3
3

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);