How to make a class JSON serializable
In order to make a class JSON serializable in Python, you need to define two methods: __init__
and to_json
. The __init__
method is used to initialize the object, and the to_json
method should return a dictionary representation of the object that can be converted to JSON.
Here is an example of a basic class that is JSON serializable:
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)
In this example, to_json
returns a dictionary that has keys 'name' and 'age' and values that are the attributes of the object. The json.dumps()
function is then used to convert the dictionary to a JSON string.
You can also use jsonpickle library to make it more easier,
import jsonpickle
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
# Create an instance of the class
obj = MyClass('John', 30)
# Convert the object to a JSON string
json_str = jsonpickle.encode(obj)
# Print the JSON string
print(json_str)
In this way you don't have to define to_json method in your class and it will automatically convert your class instance to json.