Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dynamic python object to json [duplicate]

Tags:

python

json

Possible Duplicate:
Python serializable objects json

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 ... 

Using python 2.6 the following 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__) 

yields the following error:

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

I don't know what types of subobjects a user might put into c. Is there a solution that is smart enough to detect if an attribute is an object and parse it's __dict__ automatically?

UPDATED to include subobjects on c.

like image 418
Trevor Avatar asked Sep 13 '11 21:09

Trevor


People also ask

How do you serialize a Python object to JSON?

Working With JSON Data in Python The json module exposes two methods for serializing Python objects into JSON format. dump() will write Python data to a file-like object. We use this when we want to serialize our Python data to an external JSON file. dumps() will write Python data to a string in JSON format.

Why is object not serializable Python?

Conclusion # The Python "TypeError: Object of type function is not JSON serializable" occurs when we try to serialize a function to JSON. To solve the error, make sure to call the function and serialize the object that the function returns.

What is the difference between JSON load and loads?

load() is used to read the JSON document from file and The json. loads() is used to convert the JSON String document into the Python dictionary.

What is the difference between JSON dump and JSON dumps?

dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.


2 Answers

Specify the default= parameter (doc):

json.dumps(c, default=lambda o: o.__dict__) 
like image 167
phihag Avatar answered Nov 09 '22 15:11

phihag


json.dumps(c.__dict__) 

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

like image 42
Austin Marshall Avatar answered Nov 09 '22 13:11

Austin Marshall