什麼是防止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