Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres get multiple rows into a single json object

I have a users table with columns like id, name, email, etc. I want to retrieve information of some users in the following format in a single json object:

{
    "userId_1" : {"name" : "A", "email": "[email protected]"},
    "userId_2" : {"name" : "B", "email": "[email protected]"}
}

Wherein the users unique id is the key and a json containing his information is its corresponding value.

I am able to get this information in two separate rows using json_build_object but I would want it get it in a single row in the form of one single json object.

like image 990
Basavraj Avatar asked Nov 16 '25 02:11

Basavraj


1 Answers

You can use json aggregation functions:

select jsonb_object_agg(id, to_jsonb(t) - 'id') res
from mytable t

jsonb_object_agg() aggregates key/value pairs into a single object. The key is the id of each row, and the values is a jsonb object made of all columns of the table except id.

Demo on DB Fiddle

Sample data:

id       | name | email      
:------- | :--- | :----------
userid_1 | A    | [email protected]
userid_2 | B    | [email protected]

Results:

| res                                                                                                    |
| :----------------------------------------------------------------------------------------------------- |
| {"userid_1": {"name": "A", "email": "[email protected]"}, "userid_2": {"name": "B", "email": "[email protected]"}} |
like image 197
GMB Avatar answered Nov 18 '25 15:11

GMB