简体   繁体   中英

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.

在此处输入图像描述

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM