更新JSON数组

时间:2017-03-14 11:40:11

标签: json postgresql plpgsql

我有JSON[]类型的列,我想使用concat ||运算符更新此列。

初始数据为'[{"name":"abcd","type":"pqrs"}]'

当我尝试用'[{"name":"dbca","type":"asdd"}]'

连接时

预期的结果是

'[{"name":"abcd","type":"pqrs"},{"name":"dbca","type":"asdd"}]'

但它变为'[{"name":"abcd","type":"pqrs"},[{"name":"dbca","type":"asdd"}]]'

使用的存储过程是:

CREATE OR REPLACE FUNCTION public.update_attendance(data json)
RETURNS character varying
LANGUAGE 'plpgsql' 
AS $$
DECLARE
BEGIN
       UPDATE public.amdata 
       SET attendance_data = attendance_data || data,
       WHERE something = something;
   RETURN 0;
 END;
 $$;

1 个答案:

答案 0 :(得分:0)

在这里模拟你拥有的东西:

t=# create table so14 (j json[]);
CREATE TABLE
t=# insert into so14 select '{}';
INSERT 0 1
t=# update so14 set j[1] = '{"name":"abcd","type":"pqrs"}';
UPDATE 1
t=# with a as (
select j[1],(j||'[{"name":"dbca","type":"asdd"}]'::json) ct from so14
)
select array_to_json(ct),ct[1],ct[2] from a;

t=# select array_to_json(j||'{"name":"dbca","type":"asdd"}'::json) ct from so14;
                              ct
---------------------------------------------------------------
 [{"name":"abcd","type":"pqrs"},{"name":"dbca","type":"asdd"}]
(1 row)

Time: 0.295 ms

所以你的concat按预期运行:它将'[{"name":"dbca","type":"asdd"}]]'::json追加到数组

如果你想用jsons数组构建json(如在你的问题预期部分中),你必须构建它像

t=# select array_to_json(j||'{"name":"dbca","type":"asdd"}'::json) ct from so14;
                          ct
---------------------------------------------------------------
 [{"name":"abcd","type":"pqrs"},{"name":"dbca","type":"asdd"}]
(1 row)

Time: 0.295 ms

注意我在json中删除了 [ ] 括号...

另请注意,我仅使用array_to_json来显示json[]