django-push-notifications icon indicating copy to clipboard operation
django-push-notifications copied to clipboard

Object of type UUID is not JSON serializable

Open aaronn opened this issue 3 years ago • 2 comments

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.

aaronn avatar Aug 27 '20 02:08 aaronn

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

dashdanw avatar Dec 15 '20 08:12 dashdanw

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

phuong avatar Nov 09 '21 08:11 phuong