jazzband / django-push-notifications

Send push notifications to mobile devices through GCM or APNS in Django.
MIT License
2.26k stars 613 forks source link

Object of type UUID is not JSON serializable #586

Open aaronn opened 4 years ago

aaronn commented 4 years ago

I'm passing in a UUID as a part of my extra data and getting this error Object of type UUID is not JSON serializable.

This seems to be a problem with many django packages in general that rely on the json package, and traces down to the apns2 package that actually does the sending.

Anyone have any good solutions for this? Not sure that remembering to cast my ids to str every time is a good one.

dashdanw commented 3 years ago

Try something like:

from json import JSONEncoder
from uuid import UUID

old_default = JSONEncoder.default

def new_default(obj):
         if isinstance(obj, UUID):
             return str(obj)
        return old_default(self, obj)

JSONEncoder.default = new_default
phuong commented 2 years ago

Small fix for @dashdanw suggestion:

from json import JSONEncoder
from uuid import UUID

old_default = JSONEncoder.default

def new_default(self, obj):
    if isinstance(obj, UUID):
        return str(obj)
    return old_default(self, obj)

JSONEncoder.default = new_default

Add this as "monkey patch" to your application so you can serialize an UUID to "JSON object" via json.dumps