title: How to set correct attribute names to a json aggregated result with GROUP BY clause?
body: <p>I have a table <code>temp</code> defined like this:</p>
  
  <pre><code>id |  name  |  body  | group_id
  -------------------------------
  1  | test_1 | body_1 | 1
  2  | test_2 | body_2 | 1
  3  | test_3 | body_3 | 2
  4  | test_4 | body_4 | 2
  </code></pre>
  
  <p>I would like to produce a result grouped by <code>group_id</code> and aggregated to json. However, query like this:</p>
  
  <pre><code>SELECT group_id, json_agg(ROW(id, name, body)) FROM temp
  GROUP BY group_id;
  </code></pre>
  
  <p>Produces this result:</p>
  
  <pre><code>1;[{"f1":1,"f2":"test_1","f3":"body_1"}, 
     {"f1":2,"f2":"test_2","f3":"body_2"}]
  2;[{"f1":3,"f2":"test_3","f3":"body_3"}, 
     {"f1":4,"f2":"test_4","f3":"body_4"}]
  </code></pre>
  
  <p>The attributes in the json objects are named <code>f1</code>, <code>f2</code>, <code>f3</code> instead of <code>id</code>, <code>name</code>, <code>body</code> as required. I know it is possible to alias them properly by using a subquery or a common table expression, for example like this:</p>
  
  <pre><code>SELECT json_agg(r.*) FROM (
    SELECT id, name, body FROM temp
  ) r;
  </code></pre>
  
  <p>Which produces this result:</p>
  
  <pre><code>[{"id":1,"name":"test_1","body":"body_1"}, 
   {"id":2,"name":"test_2","body":"body_2"}, 
   {"id":3,"name":"test_3","body":"body_3"}, 
   {"id":4,"name":"test_4","body":"body_4"}]
  </code></pre>
  
  <p>But I honestly don't see any way how to use it in combination with aggregation. What am I missing?</p>