Skip to content

Instantly share code, notes, and snippets.

@AlexArcPy
Created July 28, 2017 09:52
Show Gist options
  • Save AlexArcPy/2fc9f41ca164f76fcbb30ebca273b59f to your computer and use it in GitHub Desktop.
Save AlexArcPy/2fc9f41ca164f76fcbb30ebca273b59f to your computer and use it in GitHub Desktop.
Convert shapefile to GeoJSON with ogr and Python
import json
import ogr
driver = ogr.GetDriverByName('ESRI Shapefile')
shp_path = r'C:\GIS\Temp\Counties.shp'
data_source = driver.Open(shp_path, 0)
fc = {
'type': 'FeatureCollection',
'features': []
}
lyr = data_source.GetLayer(0)
for feature in lyr:
fc['features'].append(feature.ExportToJson(as_object=True))
with open('counties.json', 'wb') as f:
json.dump(fc, f)
@freestok
Copy link

freestok commented Feb 14, 2018

This mostly worked for me. The only thing I had to change was how 'counties.json' was opened:
with open('counties.json', 'w') as f:
json.dump(fc, f)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment