什么是防止python的json
库在遇到不知道如何序列化的对象时抛出异常的好方法?
我们使用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)
答案 0 :(得分:2)
这应该做你想要的。您可以在全能返回之前添加特殊情况,或自定义后备值。
import json
import datetime
class Custom_JSONEncoder(json.JSONEncoder):
def default(self, obj, **kwargs):
if isinstance(obj, datetime.datetime):
# Use the appropriate format for datetime
return obj.strftime('%Y-%m-%d %I:%M%p')
return None
答案 1 :(得分:1)
如果您不想引发TypeError,可以省略对json.JSONEncoder.default()的调用。
default()
仅针对json
不知道如何序列化的对象调用。
答案 2 :(得分:1)
我认为这样会很好:
class Rectangle(object):
def to_json(self):
return {}
class Custom_JSONEncoder(json.JSONEncoder):
def default(self, obj, **kwargs):
if hasattr(obj, 'to_json'):
return obj.to_json()
...
你需要向其他类添加方法,但对我来说这很好。