title: How to Convert Query Result to JSON Object Inside Postgres
body: <p>I have a simple query, <code>SELECT name, grp FROM things;</code> that results in the following table:</p>
  
  <pre><code> name | grp 
  ------+-----
   a    | y
   b    | x
   c    | x
   d    | z
   e    | z
   f    | z
  </code></pre>
  
  <p>I would like to end up with the following single JSON object:</p>
  
  <pre><code> {y: [a], x: [b,c], z: [d,e,f]}
  </code></pre>
  
  <p>I feel like I'm closer with the query <code>SELECT grp, array_agg(name) as names FROM things GROUP BY grp;</code> which gives three rows with the "name" condensed into an array, but I don't know where to go from here to get the rows condensed into a single JSON object.</p>
  
  <p><code>SELECT json_build_object(grp, array_agg(name)) as objects FROM things GROUP BY grp;</code> is maybe slightly closer since that results in a single column result of individual JSON objects like <code>{y: [a]}</code>, but they are still individual objects, so that might not be the right path to go down.</p>
  
  <p>This is using Postgresql 9.4.</p>