Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_agg() with dynamic column names

Tags:

postgresql

I'm trying to get the result from the table as JSON using a snippet like this.

SELECT json_agg(json_build_object('latitude',my_table.latitude,
                                  'longitude',my_table.longitude
))  from my_table;

Result:

[
  { "latitude": -24.719103042657146, "longitude": 16.97771468195161 }
]

Unfortunately, hard-coding the column names will not work since the column names are dynamic. I'm not sure how to achieve the same result without knowing exactly what the column names will be.

I've figured out that I can get the column names by doing this, but further than this I'm not too sure where to go.

SELECT column_name 
from information_schema.columns 
WHERE table_name = 'my_table';

Is my approach wrong or is there a simpler way?

like image 367
Reez0 Avatar asked Sep 18 '25 22:09

Reez0


1 Answers

You can convert a complete row to a JSON value using to_jsonb which would use the column names as the JSON keys:

select jsonb_agg(to_jsonb(t))
from (
   select latitude, longitude
   from my_table
) t

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!