topojson - encode geographic data as topology in Python

raw JSON →
1.10 verified Fri May 01 auth: no python

topojson is a Python library to encode geographic data into the TopoJSON format, which encodes topology. It supports input from GeoJSON, Shapefile, GeoDataFrame, and other sources, and can output TopoJSON, GeoJSON, or GeoDataFrames. Current version is 1.10, requiring Python >=3.8. Release cadence is irregular, roughly several months between versions.

pip install topojson
error TypeError: __init__() got an unexpected keyword argument 'ignore_index'
cause Using `ignore_index` parameter with topojson version <1.9.
fix
Upgrade topojson: pip install --upgrade topojson
error ValueError: Input data must be a dict with 'type' and 'features' keys or a GeoDataFrame
cause Passing an unsupported data format (e.g., plain list of coordinates).
fix
Wrap input in a GeoJSON FeatureCollection dict or use a GeoDataFrame.
error AttributeError: module 'topojson' has no attribute 'Topology'
cause Importing incorrectly (e.g., `import topojson` then using `topojson.Topology` but the module may not expose the class directly in old versions).
fix
Use from topojson import Topology.
gotcha Input data order is not preserved in the output TopoJSON. Topology is computed based on shared arcs, and feature order may change.
fix Do not rely on feature ordering; use properties to identify features.
breaking In version 1.9, the `ignore_index` parameter was introduced. By default, feature ids from GeoJSON source are kept unless duplicates exist. This changes previous behavior where ids were always dropped.
fix Set `ignore_index=True` in `Topology()` to restore old behavior of ignoring ids.
gotcha When using `prequantize=True` (default), coordinates are quantized to integers, which may reduce precision but also reduces file size. For lossless topology, set `prequantize=False`.
fix Use `Topology(data, prequantize=False)` for exact coordinate preservation.
deprecated In version 1.6, deprecated NumPy functions (e.g., `np.in1d`) were replaced. Issues may arise with older NumPy versions.
fix Update NumPy to a recent version (>=1.20).
conda install -c conda-forge topojson

Creates a Topology from a GeoJSON dict and outputs TopoJSON string.

from topojson import Topology
import geopandas as gpd

# Load a GeoJSON or Shapefile into a GeoDataFrame
# Example: gdf = gpd.read_file('path/to/file.geojson')
# Or use built-in example
data = {
    'type': 'FeatureCollection',
    'features': [
        {
            'type': 'Feature',
            'properties': {},
            'geometry': {
                'type': 'Polygon',
                'coordinates': [[[0,0],[1,0],[1,1],[0,1],[0,0]]]
            }
        }
    ]
}
topo = Topology(data, prequantize=False)
topojson_str = topo.to_json()
print(topojson_str[:200])