Search code examples
pythonjsongeojsongeopandasmultipolygons

How to convert geopandas dataframe with multi-polygon into geojson?


I have a Geopandas data frame with multi-polygons geometries. Now, I want to convert the data frame into geojson. So, I have converted the dataframe into dict and then used json.dump(dict) to convert the data frame into json. This works well when I have single polygon but throws error TypeError: Object of type MultiPolygon is not JSON serializable when the geometry column has multi-polygon. What is the best to convert geopandas dataframe into json seraliazble whether the geometry is multi-polygon or polygon.

df=
location    geometry    
1          MULTIPOLYGON (((-0.304766 51.425882, -0.304904...    
2          MULTIPOLYGON (((-0.305968 51.427425, -0.30608 ...    
3          MULTIPOLYGON (((-0.358358 51.423471, -0.3581 5...    
4          MULTIPOLYGON (((-0.357654 51.413925, -0.357604...

list_data = df.to_dict(orient='records')
print(json.dumps(list_data))

Error:-

TypeError: Object of type MultiPolygon is not JSON serializable

Solution

  • You could use geopandas.GeoDataFrame.to_json.

    Something like this:

    import geopandas as gpd
    from shapely.geometry import MultiPolygon, Polygon
    p1 = Polygon([(0, 0), (1, 0), (1, 1)])
    p2 = Polygon([(5, 0), (6, 0), (6, 1)])
    p3 = Polygon([(10, 0), (11, 0), (11, 1)])
    
    d = {'number': [1, 2], 'geometry': [MultiPolygon([p1, p2]), MultiPolygon([p2, p3])]}
    gdf = gpd.GeoDataFrame(d, crs="EPSG:31370")
    print(gdf.to_json())
    

    Result:

    {"type": "FeatureCollection", "features": [{"id": "0", "type": "Feature", "properties": {"number": 1}, "geometry": {"type": "MultiPolygon", "coordinates": [[[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]]], [[[5.0, 0.0], [6.0, 0.0], [6.0, 1.0], [5.0, 0.0]]]]}}, {"id": "1", "type": "Feature", "properties": {"number": 2}, "geometry": {"type": "MultiPolygon", "coordinates": [[[[5.0, 0.0], [6.0, 0.0], [6.0, 1.0], [5.0, 0.0]]], [[[10.0, 0.0], [11.0, 0.0], [11.0, 1.0], [10.0, 0.0]]]]}}]}