Skip to content

Instantly share code, notes, and snippets.

@toburger
Last active January 20, 2021 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toburger/6f1674b2f78c454d804005595e11c762 to your computer and use it in GitHub Desktop.
Save toburger/6f1674b2f78c454d804005595e11c762 to your computer and use it in GitHub Desktop.
Convert JSON array to PG array type and use it as generated column.

To convert a JSON array to be used as generated text[] column follow the steps below:

Define the following (immutable) function:

create or replace function json_array_to_pg_array(jsonarray jsonb) returns text[]
	as $$
		begin
			return (select array(select jsonb_array_elements_text(jsonarray)));
		end;
	$$ language plpgsql
	immutable
	returns null on null input

Then define your generated column by using the following snippet:

alter table <TABLENAME> add <GEN_COLUMN_NAME> text[] generated always as (
	json_array_to_pg_array(data#>'{<JSONPATH>}')
) stored
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment