Encoding objects with __geo_interface__ ------------------------------------------ >>> import geojson >>> dumps = lambda **kwargs: geojson.dumps(sort_keys=True, **kwargs) >>> class LatLon(object): ... ... def __init__(self, lat, lon): ... super(LatLon, self).__init__() ... self.lat = lat ... self.lon = lon ... ... @property ... def __geo_interface__(self): ... return dict(type="Point", coordinates=(self.lon, self.lat)) >>> lat_lon = LatLon(-54.1231, 4.53242) Can be encoded into geojson geometry: >>> json = geojson.dumps(lat_lon, sort_keys=True) >>> json # doctest: +ELLIPSIS '{"coordinates": [4..., -54...], "type": "Point"}' Objects with a __geo_interface__ attribute or property can be nested in geojson feature: >>> f = geojson.Feature(geometry=lat_lon) >>> f # doctest: +ELLIPSIS {"geometry": {"coordinates": [4..., -54...], "type": "Point"}, "id": null, "properties": {}, "type": "Feature"} And feature will encode: >>> json = geojson.dumps(f, sort_keys=True) >>> json # doctest: +ELLIPSIS '{"geometry": {"coordinates": [4..., -54...], "type": "Point"}, "id": null, "properties": {}, "type": "Feature"}' geojson types can be used to implemented a __geo_interface__: >>> class LatLon2(LatLon): ... @property ... def __geo_interface__(self): ... return geojson.Point((self.lon, self.lat)) ... >>> class LatLon2(LatLon): ... @property ... def __geo_interface__(self): ... return geojson.Point((self.lon, self.lat)) ... ... >>> ll2 = LatLon2(-54.1231, 4.53242) >>> json2 = geojson.dumps(ll2, sort_keys=True) >>> json2 # doctest: +ELLIPSIS '{"coordinates": [4..., -54...], "type": "Point"}' Decoding - to a dict >>> feature_dict = geojson.loads(json) >>> geojson.dumps(feature_dict, sort_keys=True) # doctest: +ELLIPSIS '{"geometry": {"coordinates": [4.5324200000000001, -54.123100000000001], "type": "Point"}, "id": null, "properties": {}, "type": "Feature"}' - or to an object, via a factory. Here we'll create GeoJSON object. >>> ll2 = LatLon2(43.3,-154.1) >>> json = geojson.dumps(ll2, sort_keys=True) >>> json # doctest: +ELLIPSIS '{"coordinates": [-154..., 43...], "type": "Point"}' >>> o = geojson.loads(json) # doctest: +ELLIPSIS >>> geojson.dumps(o, sort_keys=True) # doctest: +ELLIPSIS '{"coordinates": [-154..., 43...], "type": "Point"}' >>> factory = lambda ob: geojson.GeoJSON.to_instance(ob) >>> geometry = geojson.loads(json, object_hook=factory) >>> geometry # doctest: +ELLIPSIS {"coordinates": [-154..., 43...], "type": "Point"}