Serializing a user-defined class

John Bond lists at
Wed Nov 3 17:04:40 CET 2010

On 3/11/2010 3:30 PM, T.J. Simmons wrote:
> Hi all, got a question regarding serializing classes that I've 
> defined. I have some classes like
> class Foo:
>      def __init__(self, x, y):
>           self.x = x, self.y = y
> then a class that can contain multiple Foos, such as:
> class Bar:
>      def __init__(self):
>           self.foos = [Foo(a, b), Foo(1, 2)]
> While that's a gross oversimplification of the real structure (it gets 
> much, much more nested than that), that's a pretty decent overview. 
> The actual data for this is coming from a pseudo-XML file without any 
> actual structure, so I wrote a parser according to the spec given to 
> me, so I now have all the data in a series of classes I've defined, 
> with actual structure.
> What I'm wanting to do is take this data I have and spit it out into 
> JSON, but I really don't see a good way (I'm new to Python, this is my 
> first real project with it).
> I've defined a method in Foo, such as:
> def toDict(self):
>      return dict(x = self.x, y = self.y)
> but that obviously isn't going to work out like I hope when I try to 
> serialize Bar, with the multiple Foos.
> Does anyone have a great way of doing this? This has been a pretty 
> much non-stop learning/codefest the past few days and I'm out of ideas 
> for this, which is the last part of the project.
> Let me know if I can clarify in any way.
> Thanks,
> T.J.

Python has a JSON lib that may be what you want, alternatively you could 
have a common base class with a method that iterates through its own 
member variables (see dir() function) as key/value pairs, recursing when 
it finds further instances of that base class (see isinstance() 
function). That would let you iterate through all member variables in 
the object hierarchy from the top level object, and do what you wish 
with them. I'm sure there are other ways too.

Cheers, JB

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list