Home > other >  How do I convert postgreSQL results to JSON?
How do I convert postgreSQL results to JSON?

Time:11-27

I have this sql

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

It gives this results.

enter image description here

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.

CodePudding user response:

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

CodePudding user response:

try this :

WITH list AS
(
SELECT jsonb_agg(post_id) FILTER (WHERE tag = 'Politics') OVER () AS pol
     , jsonb_agg(post_id) FILTER (WHERE tag = 'Technology') OVER () AS tech 
  FROM finalcache
 ORDER BY post_rank desc
)
SELECT jsonb_build_object('Politics', l.pol, 'Technology', tech)
  FROM list AS l
  • Related