Friday, April 20, 2012

Encoding nested python object in JSON

I want to encode objects in JSON. But, I can not figure out how to make the output without the string escaping.



import json

class Abc:
def __init__(self):
self.name="abc name"
def toJSON(self):
return json.dumps(self.__dict__, cls=ComplexEncoder)

class Doc:
def __init__(self):
self.abc=Abc()
def toJSON(self):
return json.dumps(self.__dict__, cls=ComplexEncoder)

class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Abc) or isinstance(obj, Doc):
return obj.toJSON()
else:
return json.JSONEncoder.default(self, obj)

doc=Doc()
print doc.toJSON()


The result is (the dumps returns a string representation, that's why the " are escaped)



{"abc": "{\"name\": \"abc name\"}"}


I want something a little bit different. The expected result is



{"abc": {"name": "abc name"}"}


But I don't see how to...
Any hint ?



thanks in advance.





No comments:

Post a Comment