Search code examples
pythonjsongisgeojsongeopandas

Loading JSON into a GeoDataFrame


I'm having difficulty loading the following JSON containing GIS data (https://data.cityofnewyork.us/resource/5rqd-h5ci.json) into a GeoDataFrame.

The following code fails when I try to set the geometry.

import requests
import geopandas as gpd
data = requests.get("https://data.cityofnewyork.us/resource/5rqd-h5ci.json")
gdf = gpd.GeoDataFrame(data.json())
gdf = gdf.set_geometry('the_geom')
gdf.head()

Solution

  • For people who are using web mapping libraries...

    If the GeoJSON is wrapped in a FeatureCollection, as they often are when exported to a GeoJSON string by web mapping libraries (in my case, Leaflet), then all you need to do is pass the list at features to from_features() like so:

    import geopandas as gpd
    study_area = json.loads("""
     {"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[36.394272, -18.626726], [36.394272, -18.558391], [36.489716, -18.558391], [36.489716, -18.626726], [36.394272, -18.626726]]]}}]}
    """)
    gdf = gpd.GeoDataFrame.from_features(study_area["features"])
    print(gdf.head())
    

    Output:

                                                geometry
    0  POLYGON ((36.394272 -18.626726, 36.394272 -18....
    

    Easy peasy.