K
K
kondratev-ad2022-02-02 12:13:44
PostgreSQL
kondratev-ad, 2022-02-02 12:13:44

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;

It fixes something like this:
[{ "name" : "Flex", "phone": +86488},{ "name" : "Bobi", "phone": +458664}]

How do I add data to this JSON?
Let's say I want to add "city": "SanAndreas" and end up with:
[{ "name" : "Flex", "phone": +86488},{ "name" : "Bobi", "phone": +458664},{"city": "SanAndreas"}]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Melkij, 2022-02-02
@kondratev-ad

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;

A
Akina, 2022-02-02
@Akina

https://www.postgresql.org/docs/current/functions-...
JSONB concatenation operator - ||
In more complex cases - jsonb_set(), jsonb_insert() ... in general, see for yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question