Wednesday, 7 August 2013

Pythonic json serialisation

Pythonic json serialisation

I have tried to have a decent business layer that is server side. Less
work possible for each new business class to be stored in the database.
However, it doesn't perform the convertion to json very well. It works for
simple python object, using json.dumps(self.__dict__). But a list of
simple python objects does not serialize to json very well.
When performing a json serialization of a list I try to return
json.dumps([x.to_json() for x in self.my_list_items]) but it outputs
additionnal double quotes, and \" for each item in the list:
["{\"completed\": 0, \"id\": 1, \"name\": \"labelOne\"}", "{\"completed\":
0, \"id\": 2, \"name\": \"Label2\"}"]
This is the code I use:
class JSONizable(object):
def to_json(self):
return json.dumps(self.__dict__)
class Task(JSONizable):
def __init__(self):
self.id = -1
self.name = "new task"
self.completed = 1
def load_sql(self, sql):
#do things
class Tasks(JSONizable):
def __init__(self):
self.tasks=[]
def load_sql(self,sql):
#do things
def to_json(self):
return json.dumps([x.to_json() for x in self.tasks]) # things go
bad here
Could you suggest a more pythonic way to perform json serialization for
python object, when such object contains lists of items ?

No comments:

Post a Comment