我有3列的表格:
id|name|geometry
-----------------
1 |xie|geometry
我想以geojson格式获取几何体。
select id,name,ST_AsGEOJSON(geom) from table;
`o/p : `'{"id":"1","name":"xie","type":"Polygon","coordinates"[[[103.349002218076,-4.79402531349065]]]}'`
然后我使用row_to_json来组合列:
SELECT row_to_json(t) from (SELECT id,name,ST_AsGEOJSON(geom) from table where id=1)t
此命令将原始输出更改为:
o/p :`'{"id":"1","name":"xie","st_asgeojson":"{\"type\":\"Polygon\",\"coordinates\":[[[102.325742539781,-3.83353755877152]]]}"}'`
但是我希望在原始输出中没有任何改变的情况下组合列。我怎么能这样做?
答案 0 :(得分:1)
您有两种选择:
1)构建一个json,其几何体为geojson,但表示为字符串(不带引号):
SELECT row_to_json(t) FROM (
SELECT id,name,replace(ST_AsGEOJSON(geom),'"','') AS geom
FROM table where id=1
) AS t;
结果:
{"id":1,"name":"xie","geom":"{type:Polygon,coordinates:[[[0,0],[0,1],[1,1],[1,0],[0,0]]]}"}
2)用合法的geojson几何构建一个json。不幸的是,Postgres尚未真正支持将json添加到另一个json。你必须手动构建Json:
SELECT (format(
'{"id":%s,"name":%s,"geom":%s}', to_json(id), to_json(name),st_asgeojson(geom))
)::json from table where id=1;
结果:
{"id":1,"name":"xie","geom":{"type":"Polygon","coordinates":[[[0,0],[0,1],[1,1],[1,0],[0,0]]]}}