postgres change jsonb[] to jsonb

前端 未结 2 1106

I use postgres9.4, and there exists relation \"Patients\" has column \"contact\" with type jsonb[], how to transfer type jsonb[] to

相关标签:
2条回答
  • 2020-12-20 10:14

    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);
    
    0 讨论(0)
  • 2020-12-20 10:20

    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 '[]'
    
    0 讨论(0)
提交回复
热议问题