When I try to use json.dumps
on an object of a class that uses __slots__
, I get "...is not JSON serializable," or possibly an AttributeError
that __dict__
is missing. How can I get this to work? It seems that __slots__
should tell the interpreter to use a virtual dictionary for compatibility.
import json
class Foo:
__slots__ = ["bar"]
def __init__(self):
self.bar = 0
json.dumps(Foo())
Plain, vanilla json.dumps()
doesn't support custom classes, period. It doesn't matter if they use __slots__
or not here.
A popular way to handle custom classes is to use a hook that returns their __dict__
attribute instead, and that obviously won't work here. You'd have to find another way to serialise such objects.
One way would be for such objects to have a dedicated method:
class Foo:
__slots__ = ["bar"]
def __init__(self):
self.bar = 0
def json_serialize(self):
return {'bar': self.bar}
and use that in your default
hook:
json.dumps(Foo(), default=lambda o: o.json_serialize())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.