jsonable_encoder
Convert any object to something that can be encoded in JSON.
This is used internally by FastAPI to make sure anything you return can be encoded as JSON before it is sent to the client.
You can also use it yourself, for example to convert objects before saving them in a database that supports only JSON.
Read more about it in the FastAPI docs for JSON Compatible Encoder.
def jsonable_encoder(
obj: Any,
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
custom_encoder: dict[Any, Callable[[Any], Any]] | None = None,
sqlalchemy_safe: bool = True
) - > Any
Convert any object to something that can be encoded in JSON.
This is used internally by FastAPI to make sure anything you return can be encoded as JSON before it is sent to the client.
You can also use it yourself, for example to convert objects before saving them in a database that supports only JSON.
Read more about it in the FastAPI docs for JSON Compatible Encoder.
Parameters
| Name | Type | Description |
|---|---|---|
| obj | Any | The input object to convert to JSON. |
| include | `IncEx | None` = None |
| exclude | `IncEx | None` = None |
| by_alias | bool = True | Pydantic's by_alias parameter, passed to Pydantic models to define if the output should use the alias names (when provided) or the Python attribute names. |
| exclude_unset | bool = False | Pydantic's exclude_unset parameter, passed to Pydantic models to define if it should exclude from the output the fields that were not explicitly set. |
| exclude_defaults | bool = False | Pydantic's exclude_defaults parameter, passed to Pydantic models to define if it should exclude from the output the fields that had the same default value. |
| exclude_none | bool = False | Pydantic's exclude_none parameter, passed to Pydantic models to define if it should exclude from the output any fields that have a None value. |
| custom_encoder | `dict[Any, Callable[[Any], Any]] | None` = None |
| sqlalchemy_safe | bool = True | Exclude from the output any fields that start with the name _sa to avoid serializing internal SQLAlchemy state. |
Returns
| Type | Description |
|---|---|
Any | A JSON-compatible representation of the input object (e.g., dict, list, str, int) that can be serialized by standard JSON libraries. |