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)

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Binx
  • 1,350
  • 1
  • 9
  • 35
  • 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. – alphabetasoup May 25 '21 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 May 25 '21 at 22:11
  • Well I used the shell and it worked. It's pure python, but I guess it will work for now. – Binx May 25 '21 at 22:37
  • Ogr2ogr is also available as a Python function VectorTranslate. No need to use subprocess. See the API documentation https://gdal.org/python/osgeo.gdal-module.html#VectorTranslate https://gdal.org/python/osgeo.gdal-module.html#VectorTranslateOptions – user30184 May 26 '21 at 06:22

2 Answers2

18

Geopandas can accomplish this.

Try this:

import geopandas as gpd

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

Encomium
  • 3,133
  • 2
  • 14
  • 41
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')
eseglem
  • 800
  • 1
  • 5
  • 18
user30184
  • 65,331
  • 4
  • 65
  • 118