Reputation: 3659
I have table locations
:
country, city
USA, New York
USA, San Francisco
UK, London
UK, Bristol
Poland, Warsaw
Is there any way using postgres functions to generate json like this:
{
'USA': ['New York', 'San Francisco'],
'UK': ['London', 'Bristol'],
'Poland': ['Warsaw']
}
Upvotes: 0
Views: 38
Reputation: 23666
SELECT
json_object_agg(country, cities) -- 2
FROM (
SELECT
country,
json_agg(city) as cities -- 1
FROM
locations
GROUP BY country -- 1
) s
city
elements by their country
into one JSON array using json_agg()
json_object_agg()
Upvotes: 1