[GIS] OGR API get GeoJSON from string

cgdalgeojsonogr

A C# web application I'm working on needs to be able to load GeoJSON data and save it as an ESRI shapefile (either for download or to view in the browser). The GeoJSON is stored in a database and retrieved as a string.

The GDAL/OGR site says that the OGR GeoJSON driver accepts data as "text passed directly and encoded in GeoJSON" but doesn't say how to do so and there are no code samples that show how to use it.

How can I load the GeoJSON data from a string into a DataSource (or DataSet) using the GDAL/OGR API so I can export as a shapefile?

Note: I've searched GIS.SE and while GDAL OGR API GeoJSON from other datasource as string NOT file sounds like the same issue it is in fact the reverse, the OP wants to serialize the shapefile's data as GeoJSON.

Best Answer

You pass the geojson string directly to the gdal OpenEx function.

In python it's just:

# GDAL 2+
ds = gdal.OpenEx('some geojson string')


# GDAL 1.11
ds = ogr.Open('some geojson string')

An example to demonstrate:

from osgeo import gdal

geojson = '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[146.7,-41.9]}}]}'
ds = gdal.OpenEx(geojson)
layer = ds.GetLayer()
feature = layer.GetFeature(0)

print(ds.GetDriver().ShortName)
print(feature.GetGeometryRef().ExportToWkt())

Output:

GeoJSON
POINT (146.7 -41.9)
Related Question