postgres将jsonb []更改为jsonb [英] postgres change jsonb[] to jsonb

查看:76
本文介绍了postgres将jsonb []更改为jsonb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 postgres9.4 ,并且存在患者关系,其中列 contact的类型为 jsonb [] ,如何将类型 jsonb [] 转换为 jsonb

I use postgres9.4, and there exists relation "Patients" has column "contact" with type jsonb[], how to transfer type jsonb[] to 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

I have tried as the followings, contact4 is column with type 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数组的第一个元素,则问题很简单:

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);

这篇关于postgres将jsonb []更改为jsonb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆