Converting GeoJSON to Python objects?
When you load a GeoJSON file using the
json library, you get a
dict that contains an entry
features, which contains the list of features. Each feature in turn consists of a
dict, which, among other things, contains an entry
geometry is a
dict containing the entries
coordinates. So you can traverse your GeoJSON file like this:
import json with open('test.json') as f: data = json.load(f) for feature in data['features']: print feature['geometry']['type'] print feature['geometry']['coordinates']
My lib PyGeoj is specifically meant as a geojson file reader and writer, with a simple API that turns the file contents into objects with attributes, so you don't have to deal with the dictionaries directly. It also has some convenience methods, like calculate and add the bbox for the entire feature collection or just for each feature.
So for instance, the following code would do what the poster asked for:
import pygeoj testfile = pygeoj.load("test.geojson") for feature in testfile: print feature.geometry.type print feature.geometry.coordinates
The library can also import and export objects from/to other libraries via the
_geo_interface_ protocol, among other things as seen in the documentation on the project's Github page.
There are many geospatial Python modules that can convert GeoJSON to shapefiles (and the reverse):
- Pyshp 1.7 and up
- PyQGIS with the new API
see Python Geo_interface applications