How we can convert postgres array :- ARRAY['{"id": "1"}', '{"id": "2"}'] to JSONB '[{"id": "1"}, {"id": "2"}]'
Asked
Active
Viewed 1.5k times
4
priyavrat narula
- 43
- 1
- 1
- 3
-
Did you try using one of the functions here? https://www.postgresql.org/docs/11/functions-json.html – András Váczi Apr 09 '19 at 14:47
-
yes, I tried but no function seems to help – priyavrat narula Apr 09 '19 at 15:30
2 Answers
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
-
-
This is strange. Do you know why there is no
array_to_jsonbfunction? – cemper93 Aug 01 '23 at 09:48
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);