Skip to main content

to_json

Serialize a Python object to JSON including transforming and filtering data.

def to_json(
value: Any,
indent: int | None = None,
ensure_ascii: bool = False,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool = True,
exclude_none: bool = False,
round_trip: bool = False,
timedelta_mode: Literal['iso8601', 'float'] = 'iso8601',
temporal_mode: Literal['iso8601', 'seconds', 'milliseconds'] = 'iso8601',
bytes_mode: Literal['utf8', 'base64', 'hex'] = 'utf8',
inf_nan_mode: Literal['null', 'constants', 'strings'] = 'constants',
serialize_unknown: bool = False,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
polymorphic_serialization: bool | None = None,
context: Any | None = None
) - > bytes

Serialize a Python object to JSON including transforming and filtering data.

Parameters

NameTypeDescription
valueAnyThe Python object to serialize.
indent`intNone` = None
ensure_asciibool = FalseIf True, all non-ASCII characters in the output are escaped; otherwise, they are output as-is.
include`_IncExNone` = None
exclude`_IncExNone` = None
by_aliasbool = TrueWhether to use the defined alias names for fields instead of the Python attribute names.
exclude_nonebool = FalseWhether to exclude fields that have a value of None from the serialized output.
round_tripbool = FalseWhether to enable serialization and validation round-trip support.
timedelta_modeLiteral['iso8601', 'float'] = 'iso8601'Determines how timedelta objects are serialized, either as ISO 8601 strings or float values.
temporal_modeLiteral['iso8601', 'seconds', 'milliseconds'] = 'iso8601'Determines how datetime, date, and time objects are serialized (ISO 8601 string, or Unix timestamp in seconds/milliseconds).
bytes_modeLiteral['utf8', 'base64', 'hex'] = 'utf8'Determines the encoding format for bytes objects.
inf_nan_modeLiteral['null', 'constants', 'strings'] = 'constants'Determines how Infinity and NaN values are represented in the JSON output.
serialize_unknownbool = FalseWhether to attempt serializing unknown types using their string representation.
fallback`Callable[[Any], Any]None` = None
serialize_as_anybool = FalseWhether to use duck-typing serialization behavior for fields.
polymorphic_serialization`boolNone` = None
context`AnyNone` = None

Returns

TypeDescription
bytesThe serialized JSON data as a bytes object.