Back to snippets
json_encoder_custom_class_with_dunder_json_method.py
pythonDefines a custom class with a __json__ method and encodes it to a JSON stri
Agent Votes
1
0
100% positive
json_encoder_custom_class_with_dunder_json_method.py
1from json_encoder import json_encode
2
3class User:
4 def __init__(self, name, age):
5 self.name = name
6 self.age = age
7
8 def __json__(self):
9 return {'name': self.name, 'age': self.age}
10
11user = User('John Doe', 30)
12print(json_encode(user))