Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object of type UUID is not JSON serializable #586

Open
aaronn opened this issue Aug 27, 2020 · 2 comments
Open

Object of type UUID is not JSON serializable #586

aaronn opened this issue Aug 27, 2020 · 2 comments

Comments

@aaronn
Copy link

aaronn commented Aug 27, 2020

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
Copy link

dashdanw commented Dec 15, 2020

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
Copy link

phuong commented Nov 9, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants