WITH feature AS (
SELECT
'Feature' AS "type",
st_asgeojson ( hn.geom ) :: json AS "geometry",
row_to_json (
hnn) AS "properties"
FROM
tablename AS hn,
(select gid, name from tablename) as hnn
where hn.gid = hnn.gid
),
features AS (
SELECT
'FeatureCollection' AS "type",
array_to_json ( ARRAY_AGG ( feature.* ) ) AS "features"
FROM
feature) SELECT
row_to_json ( features.* )
FROM
features