什么是防止python的json
库在遇到不知道如何序列化的对象时抛出异常的好方法?防止JSON序列化在Python中抛出异常
我们使用json
来序列化字典对象,有时对象的属性不被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)
对象是一个内置的名字 – jfs