开发者

Convert dynamic python object to json [duplicate]

This question already has answers here: How to开发者_运维知识库 make a class JSON serializable (43 answers) Closed 3 months ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜