Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert recordset to json array in postgres

Tags:

sql

postgresql

i'm having one table like

  name | age 
   abc | 20
   pqr | 30

I want result in json array like

{
 [{
   "name":"abc",
   "age":20 
 },
 {
  "name":"pqr",
   "age":30 
 }]
}

I know their is method

row_to_json();

that will be give me only single row of json but i want array, please help me on this

like image 575
Abhijeet Gulve Avatar asked Dec 23 '22 18:12

Abhijeet Gulve


1 Answers

select json_agg(row_to_json(t))
from t
;
                      json_agg                      
----------------------------------------------------
 [{"name":"abc","age":20}, {"name":"pqr","age":30}]
like image 181
Clodoaldo Neto Avatar answered Jan 09 '23 06:01

Clodoaldo Neto