Last active
August 29, 2015 13:56
-
-
Save jtiai/8973519 to your computer and use it in GitHub Desktop.
Augmented JSON encoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.utils.encoding import force_unicode | |
from django.utils import datetime_safe | |
from django.utils.functional import Promise | |
import django.utils.simplejson as json | |
import datetime | |
class AugmentedJSONEncoder(json.JSONEncoder): | |
""" | |
Augmentation for simplejson encoder. | |
Now additionally encodes arbitrary iterables, class instances, decimals, | |
lazy translations, dates, times and datetimes. | |
Usage: json.dumps(data, cls=AugmentedJSONEncoder) | |
""" | |
DATE_FORMAT = "%Y-%m-%d" | |
TIME_FORMAT = "%H:%M:%S" | |
def default(self, o): | |
if(hasattr(o, "__iter__")): | |
iterable = iter(o) | |
return list(iterable) | |
elif(hasattr(o, "__add__") and hasattr(o, "__sub__") and hasattr(o, "__mul__")): | |
return float(o) | |
elif isinstance(o, datetime.datetime): | |
d = datetime_safe.new_datetime(o) | |
return d.isoformat() | |
elif isinstance(o, datetime.date): | |
d = datetime_safe.new_date(o) | |
return d.strftime(self.DATE_FORMAT) | |
elif isinstance(o, datetime.time): | |
return o.strftime(self.TIME_FORMAT) | |
elif isinstance(o, Promise): | |
return force_unicode(o) | |
elif(hasattr(o, "__class__")): | |
return o.__dict__ | |
else: | |
return str(o) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment