将PostGIS表格(postgresql)转换为GeoJSON

3
我浏览了这个问题:如何将PostgreSQL转换成GeoJSON格式? 这个PostGIS SQL可以将整个表格转换成一个GeoJSON结果:
SELECT row_to_json(fc) AS geojson FROM 
(SELECT 'FeatureCollection' As type, array_to_json(array_agg(f))
As features FROM 
(SELECT 
'Feature' As type, 
ST_AsGeoJSON((lg.geometry),15,0)::json As geometry,
row_to_json((id, name)) As properties
FROM imposm3_restaurants As lg) As f ) As fc;

我发现在结果中,我们没有得到字段的名称。

我期望输出结果如下: "properties":{"id":6323,"name":"Restaurant Sinaia"

但实际输出结果是: "properties":{"f1":6323,"f2":"Restaurant Sinaia"

我阅读了row_to_json指令的规范,因此决定更改最后一个row_to_json指令。

SELECT row_to_json(fc) AS geojson FROM 
(SELECT 'FeatureCollection' As type, array_to_json(array_agg(f))
As features FROM 
(SELECT 
'Feature' As type, 
ST_AsGeoJSON((lg.geometry),15,0)::json As geometry,
row_to_json((lg)) As properties
FROM imposm3_restaurants As lg) As f ) As fc;

现在geojson也作为属性检索geometry字段。

我的意思是,在结果中,我可以看到以geojson格式格式化的几何体,并且再次以PostGIS格式呈现(这第二个几何体不必要,我可以浪费它),因此,如果第一个结果为1200KB,则第二个结果将约为2300KB。

我该怎么办?有什么替代方案吗?

row_to_json((id, name)) As properties

或者

row_to_json((lg)) As properties

我也尝试过一些类似的事情

row_to_json(('id',lg.id ,'masa',lg.masa ,'parcela',lg.parcela)) As properties

还有其他的一些,但是没有结果(只有SQL错误)

非常感谢


嗨,约瑟!欢迎来到SO :-) 这里有一些小贴士可以帮助你提高获得回复的机会:提供一个包含一些示例数据(最好是在插入语句中)的创建表语句,当前输出和期望结果。此外,每次遇到错误时,请不要忘记发布(格式正确的)错误消息。祝编码愉快。 - Jim Jones
2个回答

9
你需要做的是首先选择你的列,然后将这个选择转换为row_to_json。 使用你的值,这将得到以下示例:
SELECT
    row_to_json(fc)
FROM (
    SELECT
        'FeatureCollection' AS type
        , array_to_json(array_agg(f)) AS features
    FROM (
        SELECT
            'feature' AS type
            , ST_AsGeoJSON(geom)::json as geometry
            , (
                SELECT
                    row_to_json(t)
                FROM (
                    SELECT
                        id
                        , name
                    ) AS t
                ) AS properties
        FROM imposm3_restaurants
    ) AS f
) AS fc

这很棒。在我的实例上表现不佳,有什么索引可以应用以使其更快?我运行的自动顾问工具没有提出任何建议。谢谢! - Snowy

-1
你可以在控制台中执行以下代码,使用ogr2ogr。
cd C:\\OSGeo4W64\\bin && ogr2ogr -f "GeoJSON" C:\Users\Documents\nameFile.json "PG:dbname=nameBD schemas=NameSchema host='localhost' port='5432' user='postgres' password='**'" -sql "select * from public.tableName"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接