Reading JSON geometries with Shapely

Although Shapely does not read or write data files, you can access geometries from outside of the library, for instance, by feeding it vector data written in json. The following script creates a polygon in json that is read into Shapely in line. Next, the mapping command returns a new, independent geometry with coordinates copied from the context:

In:    import json       from shapely.geometry import mapping, shape       p = shape(json.loads('{"type": "Polygon", "coordinates":                                            [[[1,1], [1,3 ], [3,3]]]}'))       print(json.dumps(mapping(p)))       p.areaOut:   {"type": "Polygon", "coordinates": [[[1.0, 1.0], [1.0, 3.0],                                    [3.0, 3.0], [1.0, 1.0]]]}       2.0          # result of p.area

Get Mastering Geospatial Analysis with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.