How to convert a query result to a JSON object inside Postgres

I have a simple query SELECT name, grp FROM things;, which leads to the following table:

 name | grp 
------+-----
 a    | y
 b    | x
 c    | x
 d    | z
 e    | z
 f    | z

I would like to get the following single JSON object:

 {y: [a], x: [b,c], z: [d,e,f]}

It seems to me that I'm closer to the request SELECT grp, array_agg(name) as names FROM things GROUP BY grp;, which gives three lines with "content" to the array, but I do not know where to go to get the lines compressed into one JSON object.

SELECT json_build_object(grp, array_agg(name)) as objects FROM things GROUP BY grp;may be a little closer, as this leads to a single column of the result of individual JSON objects, such as {y: [a]}, but they are still separate objects, so this may not be the right way to go down.

This uses Postgresql 9.4.

+4
source share
1 answer

, - json_object_agg, json.

: http://www.postgresql.org/docs/9.4/static/functions-aggregate.html

, :

SELECT json_object_agg(each.grp, each.names) FROM (
    SELECT grp, array_agg(name) as names FROM things GROUP BY grp
) AS each;
+4

All Articles