Source Code:
(back to article)
import json class MyClass: def __init__(self, name, age): self.name = name self.age = age def to_json(self): return { 'name': self.name, 'age': self.age } # Create an instance of the class obj = MyClass('John', 30) # Convert the object to a JSON string json_str = json.dumps(obj.to_json()) # Print the JSON string print(json_str)
Result:
Report an issue