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. This is effectively a standalone version of [SchemaSerializer.to_json][pydantic_core.SchemaSerializer.to_json].

Parameters

NameTypeDescription
valueAnyThe Python object to serialize.
indent`intNone` = None
ensure_asciibool = FalseIf True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.
include`_IncExNone` = None
exclude`_IncExNone` = None
by_aliasbool = TrueWhether to use the alias names of fields.
exclude_nonebool = FalseWhether to exclude fields that have a value of None.
round_tripbool = FalseWhether to enable serialization and validation round-trip support.
timedelta_modeLiteral['iso8601', 'float'] = 'iso8601'How to serialize timedelta objects, either 'iso8601' or 'float'.
temporal_modeLiteral['iso8601', 'seconds', 'milliseconds'] = 'iso8601'How to serialize datetime-like objects (datetime, date, time), either 'iso8601', 'seconds', or 'milliseconds'. iso8601 returns an ISO 8601 string; seconds returns the Unix timestamp in seconds as a float; milliseconds returns the Unix timestamp in milliseconds as a float.
bytes_modeLiteral['utf8', 'base64', 'hex'] = 'utf8'How to serialize bytes objects, either 'utf8', 'base64', or 'hex'.
inf_nan_modeLiteral['null', 'constants', 'strings'] = 'constants'How to serialize Infinity, -Infinity and NaN values, either 'null', 'constants', or 'strings'.
serialize_unknownbool = FalseAttempt to serialize unknown types, str(value) will be used, if that fails "< Unserializable {value_type} object >" will be used.
fallback`Callable[[Any], Any]None` = None
serialize_as_anybool = FalseWhether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization`boolNone` = None
context`AnyNone` = None

Returns

TypeDescription
bytesJSON bytes.