1

I made a mistake designing my schema. I made a column jsonb when it should have been jsonb[]. Is there a way to cast/convert the data to jsonb[]?

The data in the column is a jsonb array of text elements, it just happens to be cast as jsonb instead of jsonb[].

Something like:

select
  jsonb_to_jsonb_array(jsonb_col)
from
  mytable

The larger goal is get the column into a plain pg text array text[] such that it can be unnested. I understand how to do this with jsonb[] but am running into issues with jsonb.

8
  • jsonb[] is probably a bad choice, read this answer. Commented Jul 24, 2018 at 18:28
  • I don't think that applies here. I'm storing a flat list of strings/texts. Commented Jul 24, 2018 at 21:35
  • So you need text[]. Of course, this is your choice. Anyway, you've been warned. Commented Jul 24, 2018 at 22:08
  • Did my answer not work for you? Commented Jul 25, 2018 at 0:56
  • 1
    Awesome, glad I could help! Commented Jul 25, 2018 at 20:07

2 Answers 2

4

Use the function:

create or replace function jsonb_text_array(jsonb)
returns text[] language sql immutable as $$
    select array(select jsonb_array_elements_text($1))
$$;

alter table my_table alter jsonb_col type text[] using jsonb_text_array(jsonb_col)

DbFiddle.

Sign up to request clarification or add additional context in comments.

Comments

2

This syntax works for me

ALTER TABLE mytable
ALTER COLUMN jsonb_col TYPE JSONB[] USING ARRAY[jsonb_col]::jsonb[];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.