Convert dynamic python object to json

Question:

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__?

Asked By: Trevor

||

Answers:

json.dumps(c.__dict__)

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

Answered By: Austin Marshall

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.

Answered By: funkotron

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.

Answered By: rocksportrocker

Specify the default= parameter (doc):

json.dumps(c, default=lambda o: o.__dict__)
Answered By: phihag
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.