make a dataclass serializable as json in python

To make a dataclass serializable as JSON in Python, you can use the jsonable_encoder function from the fastapi.encoders module. This function can serialize complex objects such as dataclasses, enums, and datetime objects to JSON.

Here's an example:

main.py
from dataclasses import dataclass
from fastapi.encoders import jsonable_encoder

@dataclass
class Person:
    name: str
    age: int

person = Person(name="Alice", age=30)

# serialize dataclass to JSON
json_person = jsonable_encoder(person)
print(json_person)
# output: {"name": "Alice", "age": 30}
300 chars
15 lines

In this example, we define a Person dataclass with two fields, name and age. We then create an instance of Person and serialize it to JSON using jsonable_encoder. The resulting JSON string contains the name and age fields of the Person instance.

Note that jsonable_encoder supports many customization options, such as excluding certain fields, converting datetime objects to ISO strings, and handling custom types. Refer to the fastapi.encoders documentation for more information.

gistlibby LogSnag