2012-11-06 53 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() 
     ... 

您将需要添加方法,其他类,但对我来说,这是好的。