首页 > 解决方案 > 从查询结果生成 json

问题描述

我有桌子locations

country, city
USA, New York
USA, San Francisco
UK, London
UK, Bristol
Poland, Warsaw

有没有办法使用 postgres 函数来生成像这样的 json:

{
    'USA': ['New York', 'San Francisco'],
    'UK': ['London', 'Bristol'],
    'Poland': ['Warsaw']
}

标签: jsonpostgresql

解决方案


点击:demo:db<>fiddle

SELECT 
   json_object_agg(country, cities)    -- 2
FROM (
   SELECT
      country,
      json_agg(city) as cities         -- 1
   FROM
       locations
   GROUP BY country                    -- 1
) s
  1. city使用它们将元素聚合country到一个 JSON 数组中json_agg()
  2. 之后,您可以使用将所有行聚合到一个 JSON 对象中json_object_agg()

推荐阅读