Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

533
Vistas
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": "A@gmail.com"},
    "userId_2" : {"name" : "B", "email": "B@gmail.com"}
}

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.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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    | A@gmail.com
userid_2 | B    | B@gmail.com

Results:

| res                                                                                                    |
| :----------------------------------------------------------------------------------------------------- |
| {"userid_1": {"name": "A", "email": "A@gmail.com"}, "userid_2": {"name": "B", "email": "B@gmail.com"}} |
over 4 years ago · Santiago Trujillo Denunciar

0

try -

select row_to_json(col) from T

link below might help https://hashrocket.com/blog/posts/faster-json-generation-with-postgresql

over 4 years ago · Santiago Trujillo Denunciar

0

Try this:

SELECT json_object(array_agg(id), array_agg(json::text)) FROM ( SELECT id, json_build_object('name', name, 'email', email) as json FROM users_table ) some_alias_name

If your id is not of text type then you have to cast it to text too.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda