i want to execute the code in this question https://gis.stackexchange.com/questions/142391/storing-geojson-featurecollection-to-postgresql-with-postgis/142479#142479 but when i run the app i receive the following error:
query=""" KeyError: ' "type"'
please let me know how to fix it.
code:
def exeGeoFromGeoJSONToWKT(self): query=""" WITH data AS ( SELECT '{ "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": {"type": "Point", "coordinates": [102.0, 0.5]}, "properties": {"prop0": "value0"} }, { "type": "Feature", "geometry": { "type": "LineString", "coordinates": [ [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0] ] }, "properties": { "prop0": "value0", "prop1": 0.0 } }, { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }, "properties": { "prop0": "value0", "prop1": {"this": "that"} } } ]}'::json AS featuresCollection) SELECT LIDARDataPolygonsAsGeometry FROM ( SELECT ST_Transform(ST_SetSRID(ST_GeomFromGeoJSON(feature->>'geometry'),4326),25832) AS LIDARDataPolygonsAsGeometry FROM (SELECT json_array_elements(featuresCollection->'features') AS feature FROM data) AS f """ print(query) data = self.connection.query(query,[]) # print(data) return data
attempts:
query=""" WITH data AS ( SELECT $${ "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": {"type": "Point", "coordinates": [102.0, 0.5]}, "properties": {"prop0": "value0"} } ]}$$::json AS featuresCollection) SELECT LIDARDataPolygonsAsGeometry FROM ( SELECT ST_Transform(ST_SetSRID(ST_GeomFromGeoJSON(feature->>'geometry'),4326),25832) AS LIDARDataPolygonsAsGeometry FROM (SELECT json_array_elements(featuresCollection->'features') AS feature FROM data) AS f """
Advertisement
Answer
From the database perspective the query works just fine, but the issue seems to be in the query building. Your query has a JSON document containing multiple "
double quotes, so either you escape them ("
) or try to add the JSON to the query using parameters as described in this other answer.
Unrelated: You do not need these 3 nested subqueries. A single query would do:
WITH data AS ( SELECT '{ "type": "FeatureCollection", ... ]}'::json AS mygeojson ) SELECT ST_Transform( ST_SetSRID( ST_GeomFromGeoJSON(json_array_elements( mygeojson->'features')->>'geometry'), 4326), 25832) AS feature FROM data