In simple case if list doesn't contains geometry all works fine:

result = [dict(f.fields, id=f.id, label=f.label) for f in features]

But if result list contains geometry (Shapely) I get error object at 0xb4a87bcc> is not JSON serializable:

import geojson
result = [dict(f.fields, id=f.id, label=f.label, geom=f.geom) for f in features]

If I try to serialize not list but one dict - all works fine:


Is it possible to serialize list of dicts?


Use the mappingfunction of shapely (and the reverse: shape):

from shapely.geometry import Point, mapping, shape
point = Point(3,4)
print mapping(point)
{'type': 'Point', 'coordinates': (3.0, 4.0)}
# and the reverse
print shape(mapping(point))
POINT (3.0000000000000000 4.0000000000000000)


result = dict(fields="a", id=2, label="label", geom=mapping(point))
'{"fields": "a", "geom": {"type": "Point", "coordinates": [3.0, 4.0]}, "id": 2, "label": "label"}'
import json
'{"fields": "a", "geom": {"type": "Point", "coordinates": [3.0, 4.0]}, "id": 2, "label": "label"}'

So, in your case:

result = [dict(f.fields, id=f.id, label=f.label, geom=mapping(f.geom)) for f in features]

Look for examples of the use of Fiona on Gis StackExchange. This module uses the GeoJSON format to read and write shapefiles and other ogr formats..

import fiona
# schema of the shapefile
schema = {'geometry': 'Point', 'properties': {'id':'int:2', 'name':'str'}}
# write the shapefile with the shapely point
with fiona.open('point.shp','w','ESRI Shapefile', schema) as w:
    w.write({'geometry':mapping(point), 'properties':{'id':1, 'name':'a point'}})
# open and read the features of the shapefile
features = fiona.open('point.shp')
{'geometry': {'type': 'Point', 'coordinates': (3.0, 4.0)}, 'type': 'Feature', 'id': '0', 'properties': OrderedDict([(u'id', 1), (u'name', u'a point')])}
  • latest version of Shapely uses the geometry object: geometry.mapping(geom) – its30 Jun 5 '19 at 19:38
  • All the versions of Shapely uses the geometry object from shapely geometry import Point, mapping, shape in the script above. – gene Jun 6 '19 at 15:07
  • Sorry your syntax looked a bit foreign to me - from shapely geometry import mapping is valid python syntax? – its30 Jun 6 '19 at 15:49
  • Sorry, but this is the recommended way to import a submodule (many, many references...) – gene Jun 6 '19 at 16:43
  • 1
    Sorry and thanks, the correct version is from shapely.geometry import Point, mapping,shape – gene Jun 6 '19 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.