What is a good way to prevent the python’s json library from throwing an exception when it encounters objects that it does not know how to serialize?
We are using json to serialize dict objects, sometimes properties of the objects are not recognized by the json library, causing it to throw an exception. Instead of throwing an exception, it would be nice if it just skipped over that property of the dict instead. It could set the property value to “None” or even a message: “Cannot serialize”.
Right now, the only way I know how to do this is to explicitly identify and skip over each data type that json might encounter that will make it throw an exception. As you can see, I have it turning datetime objects into strings, but also skipping over some geo-point objects from the shapely library:
import json
import datetime
from shapely.geometry.polygon import Polygon
from shapely.geometry.point import Point
from shapely.geometry.linestring import LineString
# This sublcass of json.JSONEncoder takes objects from the
# business layer of the application and encodes them properly
# in JSON.
class Custom_JSONEncoder(json.JSONEncoder):
# Override the default method of the JSONEncoder class to:
# - format datetimes using strftime('%Y-%m-%d %I:%M%p')
# - de-Pickle any Pickled objects
# - or just forward this call to the superclass if it is not
# a special case object
def default(self, object, **kwargs):
if isinstance(object, datetime.datetime):
# Use the appropriate format for datetime
return object.strftime('%Y-%m-%d %I:%M%p')
elif isinstance(object, Polygon):
return {}
elif isinstance(object, Point):
return {}
elif isinstance(object, Point):
return {}
elif isinstance(object, LineString):
return {}
return super(Custom_JSONEncoder, self).default(object)
This should do what you want. You can add special cases before the catch-all return, or customize the fallback value.