Convert dynamic python object to json

Possible duplicate:
Python serializable json objects

I need to know how to convert a dynamic python object to JSON. An object must be able to have several children of level objects. For example:

class C(): pass class D(): pass c = C() c.dynProperty1 = "something" c.dynProperty2 = { 1, 3, 5, 7, 9 } cd = D() cddynProperty3 = "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?" cd = D() cdwhat = "d.what" json.dumps(c.__dict__) 

produces the following error:

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

I do not know what types of subobjects a user can insert in c . Is there a solution smart enough to determine if an attribute is an object and its parsing is __dict__ automatically?

UPDATED to include subobjects on c .

+46
json python
Sep 13 '11 at 21:18
source share
4 answers

Specify the default= ( doc ) parameter:

 json.dumps(c, default=lambda o: o.__dict__) 
+90
Sep 13 '11 at 10:59 a.m.
source share
 json.dumps(c.__dict__) 

This will give you a generic JSON object if that is what you are going to do.

+15
Sep 13 '11 at 21:24
source share

Try using this python-jsonpickle package

Python library for serializing any arbitrary graph of objects in JSON. It can take almost any Python object and turn the object into JSON. In addition, it can restore an object back to Python.

+7
Sep 13 2018-11-21T00:
source share

json.dumps expects a dictator to be specified as a parameter. For instance c the c.__dict__ attribute is the name of the dictionary matching attribute of the corresponding objects.

0
Sep 13 2018-11-11T00:
source share



All Articles