import jsonfrom datetime import date, datetimeclass MyClass(object): def __init__(self): self.a=1 self.b=2def _default(obj): if isinstance(obj, datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(obj, date): return obj.strftime('%Y-%m-%d') elif isinstance(obj, MyClass): return {'a':obj.a,'b':obj.b} else: #return '' #return str(obj) raise TypeError('%r is not JSON serializable' % obj)mc = MyClass()print json.dumps({'now': datetime.now(), 'today': date.today(), 'mc': mc},default=_default)#==> {"mc": {"a": 1, "b": 2}, "now": "2012-08-16 19:50:58", "today": "2012-08-16"}