Geojson to shapefile using Python

12,181

ogr2ogr appears to be a command line program - to use this you might want to look into something like subprocess.Popen():

import urllib, geojson, gdal, subprocess
url= ' http://ig3is.grid.unep.ch/istsos/wa/istsos/services/ghg/procedures/operations/geojson?epsg=4326'
response = urllib.urlopen(url)
data = geojson.loads(response.read())

with open('data.geojson', 'w') as f:
    geojson.dump(data, f)

args = ['ogr2ogr', '-f', 'ESRI Shapefile', 'destination_data.shp', 'data.geojson']
subprocess.Popen(args)

EDIT: In response to comments - yes, pickle is not the appropriate way to go about writing to the file in this case.

Share:
12,181
Gus
Author by

Gus

Updated on June 18, 2022

Comments

  • Gus
    Gus almost 2 years

    I'm trying to convert a geojson file into a shapefile. I'm trying this way (I'm very new to Python so it might be incorrect).

    import urllib, geojson, gdal
    url= ' http://ig3is.grid.unep.ch/istsos/wa/istsos/services/ghg/procedures/operations/geojson?epsg=4326'
    response = urllib.urlopen(url)
    data = geojson.loads(response.read())
    
    file = open ('data.geojson', 'w')
    pickle.dump(data,file)
    file.close()
    ogr2ogr -f "ESRI Shapefile" destination_data.shp "data.geojson"
    

    So I'm getting the data from an url, put it in a file and when I try to convert it into a shapefile I got this error:

     File "<stdin>", line 1
        ogr2ogr -f "ESRI Shapefile" destination_data.shp "data.geojson"
                                  ^
    SyntaxError: invalid syntax
    

    As I'm quite new I tried the solutions that I found on the web. Is there any way of making this work?

  • Gus
    Gus almost 7 years
    When I do this, I got another error >> ERROR 4: Failed to read GeoJSON data FAILURE: Unable to open datasource `data.geojson' with the following drivers. -> ESRI Shapefile To be honnest I'm not so sure about my way of getting the geojson. file = open ('data.geojson', 'w') pickle.dump(data,file) file.close()
  • asongtoruin
    asongtoruin almost 7 years
    @Gus you're write - I've edited my response. This does seem to write the geojson data to the file, though I can't test the ogr2ogr part unfortunately.
  • Gus
    Gus almost 7 years
    thanks, it's working now. pickle was indeed not the right way.