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

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -