python - How to make a class JSON serializable -
how make python class serializable?
a simple class:
class fileitem: def __init__(self, fname): self.fname = fname what should able output of:
json.dumps() without error (fileitem instance @ ... not json serializable)
do have idea expected output? e.g. do?
>>> f = fileitem("/foo/bar") >>> magic(f) '{"fname": "/foo/bar"}' in case can merely call json.dumps(f.__dict__).
if want more customized output have subclass jsonencoder , implement own custom serialization.
for trivial example, see below.
>>> json import jsonencoder >>> class myencoder(jsonencoder): def default(self, o): return o.__dict__ >>> myencoder().encode(f) '{"fname": "/foo/bar"}' then pass class json.dumps() method cls kwarg:
json.dumps(cls=myencoder) if want decode you'll have supply custom object_hook jsondecoder class. e.g.
>>> def from_json(json_object): if 'fname' in json_object: return fileitem(json_object['fname']) >>> f = jsondecoder(object_hook = from_json).decode('{"fname": "/foo/bar"}') >>> f <__main__.fileitem object @ 0x9337fac> >>>
Comments
Post a Comment