Added support for UUID objects to JSON serializer as well

This commit is contained in:
Armin Ronacher 2013-05-14 11:35:45 +01:00
parent 18673ba370
commit c349c91aff

View file

@ -8,6 +8,7 @@
:copyright: (c) 2012 by Armin Ronacher. :copyright: (c) 2012 by Armin Ronacher.
:license: BSD, see LICENSE for more details. :license: BSD, see LICENSE for more details.
""" """
import uuid
from datetime import datetime from datetime import datetime
from .globals import current_app, request from .globals import current_app, request
@ -30,9 +31,9 @@ __all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',
class JSONEncoder(_json.JSONEncoder): class JSONEncoder(_json.JSONEncoder):
"""The default Flask JSON encoder. This one extends the default simplejson """The default Flask JSON encoder. This one extends the default simplejson
encoder by also supporting ``datetime`` objects as well as ``Markup`` encoder by also supporting ``datetime`` objects, ``UUID`` as well as
objects which are serialized as RFC 822 datetime strings (same as the HTTP ``Markup`` objects which are serialized as RFC 822 datetime strings (same
date format). In order to support more data types override the as the HTTP date format). In order to support more data types override the
:meth:`default` method. :meth:`default` method.
""" """
@ -55,6 +56,8 @@ class JSONEncoder(_json.JSONEncoder):
""" """
if isinstance(o, datetime): if isinstance(o, datetime):
return http_date(o) return http_date(o)
if isinstance(o, uuid.UUID):
return str(o)
if hasattr(o, '__html__'): if hasattr(o, '__html__'):
return unicode(o.__html__()) return unicode(o.__html__())
return _json.JSONEncoder.default(self, o) return _json.JSONEncoder.default(self, o)