Question

I am using web.py to make a simple web service, to return an array of object. I was constructing a JSON String manually, now I want to replace it with a JSON Library. I am trying to use JSON for this purpose.

This is how I am doing it:

return json.dump(schedules.__dict__)

schedules is a list of schedule. This is how a schedule object looks like:

class Schedule:

    def __init__(self):
        self._matchDate = None
        self._matchTime = None

    @property
    def matchDate(self):
        return self._matchDate

    @property
    def matchTime(self):
        return self._matchTime

    @matchTime.setter
    def matchTime(self, value):
        self._matchTime = value

    @matchDate.setter
    def matchDate(self, value):
        self._matchDate = value

This is the error which I get:

<type 'exceptions.AttributeError'> at /Schedule
'list' object has no attribute '__dict__'
Python  /home/faizan/PycharmProjects/Soccer/Rest.py in GET, line 24
Web     GET http://localhost:8080/Schedule

How do I go about serializing the objects in JSON?

Was it helpful?

Solution

I think the proper approach here is a custom JSONEncoder that knows how to handle all your special types. Then you can do json.dump(schedules, cls=MyJSONEncoder). Here's an example for extending JSONEncoder (search for "Extending JSONEncoder").

OTHER TIPS

I guess that JSON supports only POD formats and therefore you should use other methods of serialization for your complex objects. Try pickle, but I'm not sure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top