我有 wkt 数据,我正在尝试在 PostgreSQL 中创建 JSON 输出。
我知道有一个函数 ST_AsGeoJSON ( https://postgis.net/docs/ST_AsGeoJSON.html ) 例如创建:
SELECT ST_AsGeoJSON('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)');
Output:
{"type":"LineString","coordinates":[[77.29,29.07],[77.42,29.26],[77.27,29.31],[77.29,29.07]]}
但是,我希望创建如下所示的输出:
{"type":"LineString","coordinates":[{"x":77.29,"y":29.07},{"x":77.42,"y":29.26},{"x":77.27,"y":29.31},{"x":77.29,"y":29.07}]}
请注意,我正在寻找适用于所有类型几何对象的通用解决方案。 谢谢
最佳答案
您可以使用正则表达式将 [a,b]
替换为 {"x":a,"y":b}
,如下所示:
CREATE OR REPLACE FUNCTION ST_AsCustomGeoJson(geom geometry)
RETURNS TEXT
AS
$$
-- Look for each coordinate and replace [number_a,number_b] with {"x":number_a,"y":number_b}
SELECT REGEXP_REPLACE(
ST_AsGeoJSON(geom),
'\[(-?[0-9]+\.?[0-9]*)(e\+[0-9]+)?,(-?[0-9]+\.?[0-9]*)(e\+[0-9]+)?\]',
'{"x":\1\2,"y":\3\4}',
'g');
$$
LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE;
使用新函数,您会得到预期的响应:
# Select ST_AsCustomGeoJson('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'::geometry); st_ascustomgeojson
---------------------------------------------------------------------------------------------------------------
{"type":"LineString","coordinates":[{x:77.29,y:29.07},{x:77.42,y:29.26},{x:77.27,y:29.31},{x:77.29,y:29.07}]}
(1 row)
它也应该适用于其他几何类型:
# Select ST_AsCustomGeoJson('POLYGON((0 0, 0 10, 10 10, 10 0, 0 0),(1 1, 1 9, 9 9, 9 1, 1 1))'::geometry);
st_ascustomgeojson
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
{"type":"Polygon","coordinates":[[{"x":0,"y":0},{"x":0,"y":10},{"x":10,"y":10},{"x":10,"y":0},{"x":0,"y":0}],[{"x":1,"y":1},{"x":1,"y":9},{"x":9,"y":9},{"x":9,"y":1},{"x":1,"y":1}]]}
(1 row)
# Select ST_AsCustomGeoJson('LINESTRING(3e20 3e20, 1e100 40)'::geometry);
st_ascustomgeojson
---------------------------------------------------------------------------------
{"type":"LineString","coordinates":[{"x":3e+20,"y":3e+20},{"x":1e+100,"y":40}]}
(1 row)
甚至几何集合:
# Select ST_AsCustomGeoJson('GEOMETRYCOLLECTION (POINT(-1 0), LINESTRING(4 4,5 5))');
st_ascustomgeojson
-----------------------------------------------------------------------------------------------------------------------------
---------------------------------
{"type":"GeometryCollection","geometries":[{"type":"Point","coordinates":{"x":-1,"y":0}},{"type":"LineString","coordinates":
[{"x":4,"y":4},{"x":5,"y":5}]}]}
关于postgresql - 使用 PostgreSQL 从众所周知的文本创建 GeoJSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60885021/