I recently upgraded a Django project to version 1.8, and I am happily using Postgresql and Django’s new UUIDField
. While using django-eztables to do the server-side work for DataTables.net, I ran into an issue with a UUID field.
Exception Type: TypeError
Exception Value: UUID('ff6ae150-e218-11e4-8146-bc764e04b86f') is not JSON serializable
After some reason, I found out that json
doesn’t support a plug-gable architecture, so the only transparent way to fix this was moneypatching. I put the following into my models.py file.
''' Dealing with no UUID serialization support in json ''' from json import JSONEncoder from uuid import UUID JSONEncoder_olddefault = JSONEncoder.default def JSONEncoder_newdefault(self, o): if isinstance(o, UUID): return str(o) return JSONEncoder_olddefault(self, o) JSONEncoder.default = JSONEncoder_newdefault
Hope this helps others.
This article has 3 comments
February 17, 2016
I referenced this post in a Stack Overflow question I posted today.
http://stackoverflow.com/questions/35463713/badly-formed-hexadecimal-uuid-string-error-in-django-fixture-json-uuid-conversi?noredirect=1#comment58628949_35463713
April 13, 2016
Referenced this in an SO answer myself, tweaked a bit for datetime issue:
http://stackoverflow.com/questions/23285558/datetime-date2014-4-25-is-not-json-serializable-in-django
January 9, 2017
Instead of monkey-patching, you can simply extend the JSONEncoder class. See the example with ComplexEncoder at https://docs.python.org/2/library/json.html.