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__
?
class C(object): pass
. I added an answer that should solve your problem. – Rimmaclass C(): pass
is of course valid, but it creates an old-style class (just likeclass C: pass
would) in Python 2.x. old-style classes are strange beasts. By inheriting fromobject
, you get the saner new-style behaviour. – Rimma