Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I convert postgreSQL results to JSON?

I have this sql

select post_id, tag 
from finalcache
order by tag, post_rank desc

It gives this results.

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How do i get the results to look like this?

{
   "Politics": ["1e4fd2c5-c32e-4e3f-91b3-45478bcf0185"],
   "Technology": [
      "1e4fd2c5-c32e-4e3f-91b3-45478bcf0185",
      "1e4fd2c5-c32e-4e3f-91b3-45478bcf0189",
      "1e4fd2c5-c32e-4e3f-91b3-45478bcf0186",
   ]
}

I have been trying different combinations of json_build_object and json_agg like this

select json_build_object(tag, json_agg(post_id))
from finalcache
group by tag, post_rank
order by tag, post_rank desc

But I am just not getting the correct response. Any help will be very appreciated.

>Solution :

here is how you can do it :

select json_agg(jposts) from (
     select json_build_object(tag , ARRAY_AGG(post_id)) jposts
     from mytable 
     group by tag
) t 

db<>fiddle here

first you prepare json for each row then use json_agg to aggregate all json rows

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading