0
1620
You have a simple class as follows
class MyClass:
def __init__(self):
self.name = 'Python'
self.value = 'Easy'
You want to serialize the class attributes to JSON as follows
{
"name": "Python",
"value": "Easy"
}
You can add a to_json() method to convert the attributes to class. Here is the code
import json
class MyClass:
def __init__(self):
self.name = 'Python'
self.value = 'Easy'
def to_json(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
instance = MyClass()
print(instance.to_json())
{
"name": "Python",
"value": "Easy"
}
Comment here