6

I have a found a lot of questions about converting shapefiles to GeoJSON, but how do you convert a GeoJSON to a Shapefile?

I've seen Converting GeoJSON to Shapefile using ogr2ogr? that uses ogr2ogr, but they look like they are commands for a shell.

Is there a pure Python script to do it?

I've also found this solution that runs without any errors, but the output is still a GeoJSON.

Perhaps explaining how to write as a .shp?

import geojson
import subprocess
import urllib.request as ur

url = 'http://ig3is.grid.unep.ch/istsos/wa/istsos/services/ghg/procedures/operations/geojson?epsg=3857'
response = ur.urlopen(url)
data = geojson.loads(response.read())

with open('D:/Scripts/Stand19North.geojson', 'w') as f:
    geojson.dump(data, f)

args = ['ogr2ogr', '-f', 'ESRI Shapefile', 'D:/Scripts/converted_shp.shp',
        'Stand19North.geojson']
subprocess.Popen(args)
4
  • 1
    It might be worth mentioning that the script: 1. downloads a GeoJSON and then 2. uses ogr2ogr as a subprocess. If you already have a GeoJSON file, then you may as well just run ogr2ogr on a shell, unless there's other work to do in Python. If this script works without raising an error, then you already have ogr2ogr available as a command. Commented May 25, 2021 at 22:01
  • @alphabetasoup yes I do have other work to do in Python. This script will be included in a batch that I am working on creating. That's why I am looking for a pure python way.
    – Binx
    Commented May 25, 2021 at 22:11
  • Well I used the shell and it worked. It's pure python, but I guess it will work for now.
    – Binx
    Commented May 25, 2021 at 22:37
  • Ogr2ogr is also available as a Python function VectorTranslate. No need to use subprocess. See the API documentation gdal.org/python/osgeo.gdal-module.html#VectorTranslate gdal.org/python/osgeo.gdal-module.html#VectorTranslateOptions
    – user30184
    Commented May 26, 2021 at 6:22

2 Answers 2

19

Geopandas can accomplish this.

Try this:

import geopandas as gpd

gdf = gpd.read_file('file.geojson')
gdf.to_file('file.shp')
0
8

Ogr2ogr is also available as a Python function VectorTranslate. No need to use subprocess. See the API documentation

https://gdal.org/api/python/osgeo.gdal.html#osgeo.gdal.VectorTranslate https://gdal.org/api/python/osgeo.gdal.html#osgeo.gdal.VectorTranslateOptions

Minimal usage example:

from osgeo import gdal
srcDS = gdal.OpenEx('test.json')
ds = gdal.VectorTranslate('test.shp', srcDS, format='ESRI Shapefile')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.