postgresql函数-如何将新的json对象推送到json数组?
我需要将新的json对象推送到现有的jsonpostgresql函数-如何将新的json对象推送到json数组?,sql,arrays,json,plpgsql,postgresql-9.4,Sql,Arrays,Json,Plpgsql,Postgresql 9.4,我需要将新的json对象推送到现有的json response json ='{"success":[{"aaa":"bbb"}]}'::json; newitem json ='{"ccc":"ddd"}'::json; 最后的回应如下 {"success":[{"aaa":"bbb"},{"ccc":"ddd"}]} 以下是完整的代码: DROP FUNCTION orgname.testfunction(); CREATE OR REPLACE FUNCTION orgname.tes
response json ='{"success":[{"aaa":"bbb"}]}'::json;
newitem json ='{"ccc":"ddd"}'::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$
使用9.4解决方案看起来不整洁。smth类似:
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)
错误:列引用“response”不明确,第2行:,m as(从…@Udhaya中选择json_数组_元素(response->“success”)。我为您重写了asnwer