KML to GeoJSON

raw JSON →
5.1.1 verified Mon Apr 27 auth: no python

kml2geojson is a Python library that converts KML files to GeoJSON format. Current version is 5.1.1. Actively maintained.

pip install kml2geojson
error TypeError: expected str, bytes or os.PathLike object, not dict
cause convert() takes a file path, not a dict.
fix
Pass a file path string to convert(), not a parsed KML dict.
error KeyError: 'features'
cause Output may not have a 'features' key if the GeoJSON is a single feature or non-standard.
fix
Check the structure: geojson['features'] if 'features' in geojson else geojson.
breaking Version 5.0.0 changed input/output: convert() now returns a dict instead of writing to file. Old code that expected file output will break.
fix Update code to handle return value as dict.
gotcha Input KML must be a file path or file-like object. Direct XML strings are not supported.
fix Write XML string to a temporary file or use io.StringIO with proper encoding.
deprecated Python 3.11 minimum is required in version 5.1.1. Older versions (pre-5.0) supported Python 3.6+.
fix Use Python 3.11 or newer.

Convert a KML file to GeoJSON object.

from kml2geojson import convert
import os

kml_path = 'path/to/file.kml'
if not os.path.exists(kml_path):
    print("KML file not found.")
else:
    geojson = convert(kml_path)
    # geojson is a dict that can be written as GeoJSON
    import json
    with open('output.geojson', 'w') as f:
        json.dump(geojson['features'] if 'features' in geojson else geojson, f)