【问题标题】:postgresql function - how to push new json object to json array?postgresql 函数 - 如何将新的 json 对象推送到 json 数组?
【发布时间】:2018-04-23 11:02:03
【问题描述】:

我需要将新的 json 对象推送到现有的 json。

response json ='{"success":[{"aaa":"bbb"}]}'::json;
newitem json ='{"ccc":"ddd"}'::json;

最终响应 json 应该如下所示

{"success":[{"aaa":"bbb"},{"ccc":"ddd"}]}

完整代码如下:

DROP FUNCTION orgname.testfunction();
CREATE OR REPLACE FUNCTION orgname.testfunction()
RETURNS json
    LANGUAGE 'plpgsql'
    VOLATILE
AS $RESPONSE$
DECLARE
    response json ='{"success":[]}'::json;
    newitem json ='{"ccc":"ddd"}'::json;  
BEGIN 
    with c(response,newitem) as (values('{"success":[{"aaa":"bbb"}]}'::json,'{"ccc":"ddd"}'::json))
, m as (select json_array_elements(response->'success') from c union all select newitem from c)
select concat('{"success":',json_agg(json_array_elements),'}')::json from m;
    return '{"expecting":"result"}'::json;
END;
$RESPONSE$

【问题讨论】:

    标签: sql arrays json plpgsql postgresql-9.4


    【解决方案1】:

    9.4 的解决方案看起来不整洁。比如:

    t=# with c(response,newitem) as (values('{"success":[{"aaa":"bbb"}]}'::json,'{"ccc":"ddd"}'::json))
    , m as (select json_array_elements(response->'success') from c union all select newitem from c)
    select concat('{"success":',json_agg(json_array_elements),'}')::json from m;
                       concat
    --------------------------------------------
     {"success":[{"aaa":"bbb"}, {"ccc":"ddd"}]}
    (1 row)
    

    更新

    为你的功能:

    t=# CREATE OR REPLACE FUNCTION orgname.testfunction()
    RETURNS json
        LANGUAGE 'plpgsql'
        VOLATILE
    AS $RESPONSE$
    DECLARE
        response json ='{"success":[{"aaa":"bbb"}]}'::json;
        newitem json ='{"ccc":"ddd"}'::json;
    BEGIN
      return (with c(_response,_newitem) as (values(response,newitem))
    , m as (select json_array_elements(_response->'success') from c union all select _newitem from c)
    select concat('{"success":',json_agg(json_array_elements),'}')::json from m);
    END;
    $RESPONSE$
    ;
    CREATE FUNCTION
    t=# select * from orgname.testfunction();
                    testfunction
    --------------------------------------------
     {"success":[{"aaa":"bbb"}, {"ccc":"ddd"}]}
    (1 row)
    

    【讨论】:

    • ERROR: column reference "response" is ambiguous LINE 2: , m as (select json_array_elements(response->'success') from...
    • @Udhaya 我为你重写了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 2018-01-25
    • 1970-01-01
    • 2018-11-10
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多