什么是防止pythonjson
库在遇到不知道如何序列化的对象时抛出异常的好方法?
我们json
用于序列化dict对象,有时json
库无法识别对象的属性,导致它抛出异常。如果它只是跳过 dict 的该属性而不是抛出异常,那就太好了。它可以将属性值设置为“无”甚至是一条消息:“无法序列化”。
现在,我知道如何做到这一点的唯一方法是明确识别并跳过json
可能遇到的每种数据类型,这将使其引发异常。如您所见,我将datetime
对象转换为字符串,但也跳过了shapely
库中的一些地理点对象:
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)