Skip to main content

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

NameTypeDescription
objAnyThe input object to convert to JSON.
include`IncExNone` = None
exclude`IncExNone` = None
by_aliasbool = TruePydantic'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_unsetbool = FalsePydantic'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_defaultsbool = FalsePydantic'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_nonebool = FalsePydantic'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_safebool = TrueExclude from the output any fields that start with the name _sa to avoid serializing internal SQLAlchemy state.

Returns

TypeDescription
AnyA JSON-compatible representation of the input object (e.g., dict, list, str, int) that can be serialized by standard JSON libraries.