Answer the question
In order to leave comments, you need to log in
How to add key:value to JSON in PostgreSQL?
There is a table table_1 with names and phones. In my function, I collect JSON from it and send it to Rabbit.
id | name | phone
1 | Flex | +86488
2 | Bobby | +458664
DECLARE my_data json;
BEGIN
SELECT array_to_json(array_agg(row_to_json (r))) into my_data FROM (
SELECT name, phone
FROM table_1
) r;
RETURN amqp.publish(1, ''::varchar, 'queue'::varchar, my_data::varchar);
END;
[{ "name" : "Flex", "phone": +86488},{ "name" : "Bobi", "phone": +458664}]
[{ "name" : "Flex", "phone": +86488},{ "name" : "Bobi", "phone": +458664},{"city": "SanAndreas"}]
Answer the question
In order to leave comments, you need to log in
array_to_json (array_agg (row_to_json (r)))
is not the first time I see such a construct, but I don’t understand why it is necessary in such an overcomplicated form. If you found array_agg, then you might have noticed json_agg in the same place, which leads to the simplest select json_agg (r) from r
There is no concatenation operator for json, take jsonb:
select jsonb_agg(r) || jsonb_build_object('city', 'SanAndreas') from tablename r;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question