Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
TopoJSON to GeoJSON converter
Convert topojson to geojson
Example Usage:
python data.topojson data.geojson
The topojson tested here was created using the mbostock topojson CLI
created with --spherical coords and --properties turned on
Author: Matthew Perry (
Thanks to @sgillies for the topojson geometry logic
Next steps: how can this be generalized to a robust CLI converter?
import json
import sys
from topojson import geometry
from shapely.geometry import asShape
topojson_path = sys.argv[1]
geojson_path = sys.argv[2]
with open(topojson_path, 'r') as fh:
f =
topology = json.loads(f)
# file can be renamed, the first 'object' is more reliable
layername = topology['objects'].keys()[0]
features = topology['objects'][layername]['geometries']
scale = topology['transform']['scale']
trans = topology['transform']['translate']
with open(geojson_path, 'w') as dest:
fc = {'type': "FeatureCollection", 'features': []}
for id, tf in enumerate(features):
f = {'id': id, 'type': "Feature"}
f['properties'] = tf['properties'].copy()
geommap = geometry(tf, topology['arcs'], scale, trans)
geom = asShape(geommap).buffer(0)
assert geom.is_valid
f['geometry'] = geom.__geo_interface__
echo "Convert ESRI File Geodatabase to a shapefile in Plate Carre/WGS84 (EPSG:4326)"
ogr2ogr -t_srs epsg:4326 -f "ESRI Shapefile" \
ecoregions_original.shp EcoSums_ForMatt
echo "Convert shapefile to topojson with simplification"
# -s <tolerance> measured in steridians
# see
# alternatively, can specify proportion of points kept
# e.g. --simplify-proportion 0.1 \
# rm temp*
for tolerance in 1E-7 1E-8 1E-9 1E-10
topojson --spherical \
--properties \
-s $tolerance \
-q 1E6 \
-o temp_$tolerance.topojson \
ecoregions_original.shp &&
# Convert it to GeoJSON
python temp_$tolerance.topojson temp_$tolerance.geojson &&
# Optionally, convert GeoJSON to any OGR data source
ogr2ogr -f "ESRI Shapefile" ecoregions_$tolerance.shp temp_$tolerance.geojson OGRGeoJson &
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment