2012-11-06 51 views
3

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

對象是一個內置的名字 – jfs

回答

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 
+0

,如果你不使用'超()'可能調用除了json.JSONEncoder其他類,然後你可以將整個try/except塊。 – jfs

+0

@ J.F.Sebastian啊,對不對:P – pydsigner

1

你可以省略調用json.JSONEncoder.default()如果你不想養類型錯誤。 default()只稱爲該json不知道如何序列化對象。

+0

希望我能接受兩個答案。 –

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() 
     ... 

您將需要添加方法,其他類,但對我來說,這是好的。