Also got this nice suggestion at https://stackoverflow.com/q/48050127/165071 -
SELECT COALESCE( json_object_agg( gid, array_to_json(y) ), '{}'::json) FROM ( SELECT gid, array_agg( json_build_object( 'uid', uid, 'created', EXTRACT(EPOCH FROM created)::int, 'msg', msg) ) AS y FROM chat /* WHERE gid = 0 */ GROUP BY gid ) x;