Convert dynamic python object to json [duplicate]
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 ...
I tried this 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__)
but I got an error that says TypeError: <__main__.D instance at 0x99237ec> is not JSON serializable
.
How can I make it so that any sub-objects that are classes are automatically serialized using their __dict__
?
Specify the default=
parameter (doc):
json.dumps(c, default=lambda o: o.__dict__)
json.dumps(c.__dict__)
That will give you a generic JSON object, if that's what you're going for.
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.
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.
精彩评论