【问题标题】:postgres change jsonb[] to jsonbpostgres 将 jsonb[] 更改为 jsonb
【发布时间】:2016-05-13 11:12:17
【问题描述】:

我使用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\"}"}

我试过如下,contact4jsonb类型的列

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\"}"}

【问题讨论】:

  • 试试... using contact4[1]

标签: postgresql postgresql-9.4


【解决方案1】:

如果只使用 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($1), jsonb_each(unnest)
$$;

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 好点,to_json()to_jsonb() 保留了数组的结构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    相关资源
    最近更新 更多