0

I need to push new json object to existing json.

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

Final response json should like below

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

Here is the complete code:

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$

1 Answer 1

1

with 9.4 solution will not look neat. smth like:

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)

update

for your function:

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)
Sign up to request clarification or add additional context in comments.

2 Comments

ERROR: column reference "response" is ambiguous LINE 2: , m as (select json_array_elements(response->'success') from...
@Udhaya I rewrote the asnwer for you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.