You can create a feature collection by using row_to_json, selecting 'FeatureCollection' as type, and rolling up all you geometries into an array using array_to_json(array_agg(geom)) in a subquery, which creates the appropriate GeoJSON using ST_AsGeoJSON.
You can also add the EPSG:4326 as a crs attribute, at the top level of the GeoJSON. When you are creating keys and values, the trick is to realize that, for example, Select name as type gets converted into type:name and (SELECT properties FROM (SELECT 'EPSG:4326' AS name) AS properties) becomes properties:{'name':EPSG:4326} once the whole lot is wrapped up by the row_to_json function.
Replace your_table with your table name in the below.
SELECT row_to_json(featcoll)
FROM
(SELECT 'FeatureCollection' AS type,
(SELECT crs FROM
(SELECT 'name' AS type,
(SELECT properties
FROM (SELECT 'EPSG:4326' AS name) AS properties)
) AS crs),
array_to_json(array_agg(feats)) AS features
FROM (SELECT
'Feature' AS type,
ST_AsGeoJSON(geom)::JSON AS geometry
FROM your_table)
AS feats
) AS featcoll;
or with some test data,
WITH test_geoms(geom) AS
(VALUES(ST_MakePoint(0,0)), (ST_MakePoint(1,1)))
SELECT row_to_json(featcoll)
FROM
(SELECT 'FeatureCollection' AS type,
(SELECT crs FROM
(SELECT 'name' AS type,
(SELECT properties
FROM (SELECT 'EPSG:4326' AS name) AS properties)
) AS crs),
array_to_json(array_agg(feats)) AS features
FROM (SELECT
'Feature' AS type,
ST_AsGeoJSON(geom)::JSON AS geometry
FROM test_geoms)
AS feats
) AS featcoll;
which produces:
{
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "EPSG:4326"
}
},
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [0, 0]
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [1, 1]
}
}]
}
select row_to_json(foo) from (select name from test_table limit 1) as foo;– user30184 Jun 10 '16 at 13:14