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.py300 chars15 linesIn 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