简体   繁体   English

有没有办法从 POSTGRESQL 中的 json 数组中提取坐标

[英]Is there a way to extract from coordinates from this json array in POSTGRESQL

I have this column "region" that has the following jsonb value我有此列“区域”,它具有以下 jsonb 值

{ "type": "FeatureCollection"
, "features": [{
      "type": "Feature"
    , "geometry": { 
        "type": "Polygon"
      , "coordinates": [[
          [-105.31219482421875, 39.37252570201878]
        , [-104.403076171875, 39.37252570201878]
        , [-104.403076171875, 40.195659093364654]
        , [-105.31219482421875, 40.195659093364654]
        , [-105.31219482421875, 39.37252570201878]
        ]]
      }
    , "properties": {}
    }]
}

I'm trying to figure out how to extract the coordinate values from this nested json我试图弄清楚如何从这个嵌套的 json 中提取坐标值

On recent versions of PostgreSQL, it is possible to use json path queries to reshape the data succinctly.在最新版本的 PostgreSQL 上,可以使用 json 路径查询来简洁地重塑数据。

create table x (jsonb_data) as 
select jsonb '{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Polygon", "coordinates": [[[-105.31219482421875, 39.37252570201878], [-104.403076171875, 39.37252570201878], [-104.403076171875, 40.195659093364654], [-105.31219482421875, 40.195659093364654], [-105.31219482421875, 39.37252570201878]]]}, "properties": {}}]}' jsonb_data;

SELECT
  jsonb_data
, (coord ->> 0)::float coord0
, (coord ->> 1)::float coord1
FROM x
JOIN LATERAL jsonb_path_query(
    jsonb_data
  , '$.features[*].geometry.coordinates[*][*]') coord 
          ON TRUE

Not going into too much detail, here's a bit of background of the various more advanced bits in this query:不谈太多细节,这里是这个查询中各种更高级的位的一些背景:

jsonb_path_query function was introduced in version 12 jsonb_path_query function 在版本 12 中引入

JOIN LATERAL... ON TRUE in this query evaluates the expression ... for each row, and the evaulated expression unnests queries the json & unnests the resulting array. JOIN LATERAL... ON TRUE在此查询中计算表达式...对于每一行,并且计算的表达式取消嵌套查询unnests并取消嵌套结果数组。

(coord ->> 0)::float extracts the first numeric value from each coordinate list and converts it to a postgresql float. (coord ->> 0)::float从每个坐标列表中提取第一个数值并将其转换为 postgresql 浮点数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM