TransWikia.com

Converting (Polyline Data) JSON to GeoDataFrame using GeoPandas

Geographic Information Systems Asked by sutan on August 20, 2020

I have this particular json and I want to make the JSON into a GeoDataFrame (with geometry and its attributes); How to set the geometry and attributes to a geodataframe?


I have tried using geopandas.read_file() and it returned an error: "expected string or bytes-like object";

I also tried geopandas.GeoDataFrame.from_features() but it returns this table (which is the problem):

wrong form of geodataframe

I want it to look like something like this (a geometry column, and the other attribute columns):
the right geodataframe
I am aware of Esri’s ArcGIS API for Python but, in this case, I can’t use ArcGIS API or ArcPy.
Thank you.

2 Answers

GeoPandas uses Shapely to define geometry. so Using shapely we can define a function to grab the json, cleans it, and convert the geometry into a shapely object. Here's how to convert the json into a GeoDataFrame:

with link = web service, then;

# function "get_line" should retrieve the JSON and returns a GeoDataFrame
# if it's a polygon, then the import shapely must be "Polygon" and ...
# ... the ['paths'] must be ['rings']

def get_line(base_link, objid):
    from shapely.geometry import LineString
    iterator=objid
    link=base_link + "/" + str(objid) + "?f=pjson"
    print(link)
    js = r.get(link, verify=False).json()
    df = pd.DataFrame(js['feature']['attributes'], index=[0])
    df['geom']=LineString(js['feature']['geometry']['paths'][0])
    crs = {'init': 'epsg:4326'}
    gdf = gpd.GeoDataFrame(df, crs=crs).set_geometry(df['geom'])
    return gdf

link = "insert link to web service, here"
get_line(link,1)

Correct answer by sutan on August 20, 2020

I'm guessing r in r.get is the requests library and its return a json object? If so, you can just convert your request to a string and use read_file into a GeoDataFrame.

url = "https://..."
gdf = gpd.read_file(r.get(url).text)

Answered by tynowell on August 20, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP