Skip to content

Instantly share code, notes, and snippets.

@letam
Created January 24, 2020 16:09
Show Gist options
  • Save letam/baa4708825a77fb91b742b5a9b2fd9cb to your computer and use it in GitHub Desktop.
Save letam/baa4708825a77fb91b742b5a9b2fd9cb to your computer and use it in GitHub Desktop.
Return json-friendly version of a data structure in Django project
import datetime
import decimal
import uuid
from django.utils.duration import duration_iso_string
from django.utils.functional import Promise
from django.utils.timezone import is_aware
def json_friendly(o):
"""
Return a JSON-friendly version of the provided value.
Based on code of `django.core.serializers.json.DjangoJSONEncoder.default`.
"""
if isinstance(o, datetime.datetime):
r = o.isoformat()
if o.microsecond:
r = r[:23] + r[26:]
if r.endswith('+00:00'):
r = r[:-6] + 'Z'
return r
elif isinstance(o, datetime.date):
return o.isoformat()
elif isinstance(o, datetime.time):
if is_aware(o):
raise ValueError("JSON can't represent timezone-aware times.")
r = o.isoformat()
if o.microsecond:
r = r[:12]
return r
elif isinstance(o, datetime.timedelta):
return duration_iso_string(o)
elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
return str(o)
elif isinstance(o, dict):
return {key: json_friendly(value) for key, value in o.items()}
else:
return o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment