In Python, the json
module allows for custom types to be serialized via either the cls
or default
named arguments. However, this does not seem to work for the keys in a dictionary as per the following code snippet.
import json
import uuid
# works
mydict = {
'helo': uuid.uuid4(),
'world': uuid.uuid4(),
}
print(json.dumps(mydict, default=str))
# raises TypeError: keys must be str, int, float, bool or None, not UUID
mydict = {
uuid.uuid4(): 'helo',
uuid.uuid4(): 'world',
}
print(json.dumps(mydict, default=str))
This is an oversight? A bug? Why would default
not also be used as a fallback method for serializing the keys?