Last active
September 14, 2020 04:09
-
-
Save polkovnikov/5034fb97a5150edfabb40c6206a76149 to your computer and use it in GitHub Desktop.
Converts ESRI Shapefile (.shp) to GeoJSON (.json, see http://geojson.org/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Converts ESRI Shapefile (.shp) to GeoJSON (.json, see http://geojson.org/). | |
# Usage: python shp_to_json.py SHAPEFILE_NAME.shp | |
import sys, os, json | |
# python -m pip install pyshp | |
import shapefile | |
ifn = sys.argv[1] | |
assert ifn.lower().endswith('.shp'), ifn | |
ofn = ifn[:ifn.rfind('.')] + '.json' | |
assert not os.path.exists(ofn), f'File already exists "{ofn}"!' | |
r = shapefile.Reader(ifn) | |
def ToJsonTypes(o): | |
if type(o) in [int, float, str, bool, type(None)]: | |
return o | |
elif type(o) is dict: | |
return {ToJsonTypes(k) : ToJsonTypes(v) for k, v in o.items()} | |
elif type(o) in [shapefile._Array, list, tuple]: | |
return [ToJsonTypes(e) for e in o] | |
else: | |
assert False, type(o) | |
jd = json.dumps(ToJsonTypes(r.__geo_interface__), indent = 4, ensure_ascii = False).encode('utf-8') | |
with open(ofn, 'wb') as f: | |
f.write(jd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment