1

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. May 25 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.
    – Zman3
    May 25 at 22:11
  • Well I used the shell and it worked. It's pure python, but I guess it will work for now.
    – Zman3
    May 25 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
    May 26 at 6:22
3

Geopandas can accomplish this.

Try this:

import geopandas as gpd

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

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

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, privacy policy and cookie policy

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