mashumaro is a fast and well-tested serialization library built on top of Python dataclasses. It provides efficient conversion of dataclass instances to and from various formats like JSON, YAML, TOML, MessagePack, and plain dictionaries. It is actively maintained with frequent releases, currently at version 3.20.
pip install mashumaroVerified import paths — ran on the pinned version, not inferred.
Define a dataclass inheriting from `DataClassJSONMixin` to automatically gain `to_json()` and `from_json()` methods for seamless JSON serialization and deserialization.
Review deserialization logic for fields using `Union` or basic types to align with the new, more precise behavior. Explicitly define serialization/deserialization strategies if specific coercions are required.
Upgrade Python to 3.9 or higher, or pin `mashumaro<3.15` in your project dependencies.
Upgrade to mashumaro v3.13.1 or later to get correct type annotations for `DataClassORJSONMixin.to_json`. Consider using `to_jsonb()` if byte output is desired for performance.
Use Mixins when your root data structure is a dataclass. Use Codecs when you need to serialize/deserialize arbitrary types (like a `List[datetime]`) or top-level collections that are not directly represented by a single dataclass.
Be explicit with `forbid_extra_keys` in your `Config` if you want strict validation. If using `Alias(...)` for field aliasing and require deserialization by both alias and original field name, set `allow_deserialization_not_by_alias=True` in your dataclass `Config`.
Ensure that the input data for deserialization contains all non-optional fields required by the dataclass. For example, if 'name: str' is a field, the input dictionary must have a 'name' key.
Either ensure the input dictionary only contains keys corresponding to dataclass fields, or set `forbid_extra_keys = False` in your dataclass's `Config` or `code_generation_options` during deserialization if you want to ignore extra keys.
Define a custom serialization strategy for the field's type using `mashumaro.types.SerializationStrategy` or `mashumaro.types.SerializableType`, or ensure the field's type is one of Mashumaro's natively supported types or a dataclass itself.
Install the required optional dependency using pip, often with Mashumaro's extras, like `pip install mashumaro[orjson]` for ORJSON support or `pip install mashumaro[yaml]` for YAML support.