views:

88

answers:

2

So, that's the question:
How to make a class serializable?

a simple class:

class FileItem:
    def __init__(self, fname):
        self.fname = fname

What should I do to be able to get output of:

json.dumps()

without an error (FileItem instance at ... is not JSON serializable)

A: 

Here's a blog posting talking about serializing an arbitrary python object to work with JSON using dict.

wheaties
+3  A: 

Do you have an idea about the expected output? For e.g. will this do?

>>> f  = FileItem("/foo/bar")
>>> magic(f)
'{"fname": "/foo/bar"}'

In that case you can merely call json.dumps(f.__dict__).

If you want more customized output then you will have to subclass JSONEncoder and implement your own custom serialization.

For a trivial example, see below.

>>> from json import JSONEncoder
>>> class MyEncoder(JSONEncoder):
    def default(self, o):
        return o.__dict__    

>>> MyEncoder().encode(f)
'{"fname": "/foo/bar"}'

If you also want to decode then you'll have to supply a custom object_hook to the JSONDecoder class. For 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 at 0x9337fac>
>>> 
Manoj Govindan
thank you for a full answer!
Sergey