I have a text[] column which consists of elements of stringified JSON, and I want to convert it to jsonb[].
Here is my table reduced to the relevant text[] column:
CREATE TABLE certificate (
...
criterias text[]
...
)
An example criterias column looks like this:
'{"{\"url\":\"https://criteria.com\", \"description\":\"My Criteria\"}","{\"url\":\"https://criteria2.com\", \"description\":\"Other Criteria\"}"}'
Each criteria is of the same format.
I want to convert the type of the criterias column to be jsonb[].
How can I achieve this? I am using Postgres 15.4.
Basically,
to_jsonb()converts a Postgres array into a JSON array automatically.But your case is not so simple. You stored
jsonbliterals as elements of a text array (text[]). So you must cast each element (or the whole array) tojsonbexplicitly.For completely valid JSON literals, there is a shortcut with direct casts and
textas stepping stone. Because thetextrepresentation happens to be identical. (No custom function required.):fiddle
To convert to an actual
jsonbcolumn (the more commonly used setup), unnest and cast elements individually. I suggest a temporary function:Then:
fiddle
To get an array of
jsonbvalues (jsonb[]), use a function witharray_agg()instead ofjsonb_agg(), andRETURNS jsonb[]:fiddle
The rest is mostly the same. Might be useful to do more than just type conversion. Else the plain cast at the top is simpler.
If the column has a column
DEFAULT, you may have to drop and recreate that with proper type. See:Note that either results in a complete table rewrite, which takes an exclusive lock on the table for the duration. See:
About temporary functions:
About SQL-standard functions: