postgres 将 jsonb[] 更改为 jsonb

postgres change jsonb[] to jsonb

我使用 postgres9.4,并且存在关系 "Patients" 具有类型 jsonb[] 的列 "contact",如何将类型 jsonb[] 转换为 jsonb?

记录如下。

=>select name, contact from "Patients" where contact is not null;

name  |                                               contact                                               
--------+-----------------------------------------------------------------------------------------------------
"tom" | {"{\"name\": \"tom\", \"phone\": \"111111\", \"address\": \"shanghai\", \"relation\": \"your_relation\"}"}

我试过如下,contact4 是类型为 jsonb

的列
alter table "Patients" alter column contact4 type jsonb using contact4::text::jsonb;

ERROR:  invalid input syntax for type json
DETAIL:  Expected ":", but found "}".
CONTEXT:  JSON data, line 1: ...ress\": \"shanghai\", \"relation\": \"your_relation\"}"}

如果只用到jsonb数组的第一个元素,问题就简单了:

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

否则你可以使用以下函数:

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

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

从 9.5 版本开始,要保留数据并将数据保存在 json 中作为数组,这会更好。

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 '[]'