postgres change jsonb[] to jsonb

偶尔善良 提交于 2019-11-29 13:07:58

If only the first element of jsonb array is used then the issue is simple:

alter table "Patients" alter column contact type jsonb using contact[1]::jsonb;

else you can use the following function:

create or replace function jsonb_array_to_jsonb(jsonb[])
returns jsonb language sql as $$
    select jsonb_object_agg(key, value)
    from unnest($1), jsonb_each(unnest)
$$;

alter table "Patients" alter column contact type jsonb using jsonb_array_to_jsonb(contact);

As of 9.5 version, to preserve the data and keep the data in json as array this would work much better.

ALTER TABLE "Patients"  ALTER COLUMN "contact" DROP DEFAULT
ALTER TABLE "Patients"  ALTER COLUMN "contact" TYPE jsonb USING to_json(contact)
ALTER TABLE "Patients"  ALTER COLUMN "contact" SET DEFAULT '[]'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!