python class to json code example

Example 1: python object to json

jsonStr = json.dumps(myobject.__dict__)

Example 2: convert class object to json python

import json

class Laptop:
	name = 'My Laptop'
	processor = 'Intel Core'
		
#create object
laptop1 = Laptop()
laptop1.name = 'Dell Alienware'
laptop1.processor = 'Intel Core i7'

#convert to JSON string
jsonStr = json.dumps(laptop1.__dict__)

#print json string
print(jsonStr)

Example 3: python class json serializable

import json

class Object:
    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__, 
            sort_keys=True, indent=4)