简体   繁体   English

如何将 postgreSQL 结果转换为 JSON?

[英]How do I convert postgreSQL results to JSON?

I have this sql我有这个 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我一直在尝试这样的json_build_objectjson_agg的不同组合

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 db<> 在这里摆弄

first you prepare json for each row then use json_agg to aggregate all json rows首先为每一行准备 json 然后使用json_agg聚合所有 json 行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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