Convert dynamic python object to json

PythonJson

Python Problem Overview


> Possible Duplicate:
> Python serializable objects json

I need to know how to convert a dynamic python object into JSON. The object must be able to have multiple levels object child objects. For example:

class C(): pass
class D(): pass

c = C()
c.dynProperty1 = "something"
c.dynProperty2 = { 1, 3, 5, 7, 9 }
c.d = D()
c.d.dynProperty3 = "d.something"

# ... convert c to json ...

Using python 2.6 the following code:

import json
 
class C(): pass
class D(): pass
 
c = C()
c.what = "now?"
c.now = "what?"
c.d = D()
c.d.what = "d.what"
 
json.dumps(c.__dict__)

yields the following error:

TypeError: <__main__.D instance at 0x99237ec> is not JSON serializable

I don't know what types of subobjects a user might put into c. Is there a solution that is smart enough to detect if an attribute is an object and parse it's __dict__ automatically?

UPDATED to include subobjects on c.

Python Solutions


Solution 1 - Python

Specify the default= parameter (http://docs.python.org/library/json.html#json.dump">doc</a>)</sup>;:

json.dumps(c, default=lambda o: o.__dict__)

Solution 2 - Python

json.dumps(c.__dict__)

That will give you a generic JSON object, if that's what you're going for.

Solution 3 - Python

Try using this package python-jsonpickle

> Python library for serializing any arbitrary object graph into JSON. It can take almost any Python object and turn the object into JSON. Additionally, it can reconstitute the object back into Python.

Solution 4 - Python

json.dumps expects a dictonary as a parameter. For an instance c, the attribute c.__dict__ is a dictionary mapping attribute names to the corresponding objects.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTrevorView Question on Stackoverflow
Solution 1 - PythonphihagView Answer on Stackoverflow
Solution 2 - PythonAustin MarshallView Answer on Stackoverflow
Solution 3 - PythonfunkotronView Answer on Stackoverflow
Solution 4 - PythonrocksportrockerView Answer on Stackoverflow