json - 从查询结果生成 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']
}
解决方案
SELECT
json_object_agg(country, cities) -- 2
FROM (
SELECT
country,
json_agg(city) as cities -- 1
FROM
locations
GROUP BY country -- 1
) s
city
使用它们将元素聚合country
到一个 JSON 数组中json_agg()
- 之后,您可以使用将所有行聚合到一个 JSON 对象中
json_object_agg()
推荐阅读
- elasticsearch - Google Colaboratory - 我可以使用它连接到本地服务器吗?
- c# - 如何从 Blazor @code 块中的单选/复选框表单提交中获取数据?
- python - 无法导入名称 EmailMessage
- r - 如何在保留正确结构/顺序的同时将 Matlab 表(“单元”结构)导入 R 数据框?
- azure - 自动缩放后的 Azure 文件系统
- c - 为什么元素不留在数组中?
- python - Python pygame 多次对同一图像进行 blit
- c++ - 删除默认控制台空格
- json - Python - 在数组中搜索特定值
- python - Python子进程git提交消息只接受单个字符串