{"id":476,"library":"dataclasses-json","title":"Dataclasses JSON","description":"Dataclasses JSON is a Python library that provides a simple API for easily serializing dataclasses to and from JSON. It leverages the built-in `dataclasses` module and internally uses `marshmallow` for robust schema generation and deserialization, supporting complex types like nested dataclasses and various collections. The current version is 0.6.7, and it maintains an active release cadence with frequent bug fixes and feature enhancements.","status":"active","version":"0.6.7","language":"python","source_language":"en","source_url":"https://github.com/lidatong/dataclasses-json","tags":["dataclasses","json","serialization","deserialization","marshmallow","type-hints"],"install":[{"cmd":"pip install dataclasses-json","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Core functionality for Python <3.7 (backport). Built-in for Python >=3.7.","package":"dataclasses","optional":true},{"reason":"Used internally for schema generation and advanced deserialization logic.","package":"marshmallow","optional":false}],"imports":[{"symbol":"dataclass_json","correct":"from dataclasses_json import dataclass_json"},{"symbol":"DataClassJsonMixin","correct":"from dataclasses_json import DataClassJsonMixin"},{"symbol":"LetterCase","correct":"from dataclasses_json import LetterCase"}],"quickstart":{"code":"from dataclasses import dataclass\nfrom dataclasses_json import dataclass_json, LetterCase\n\n@dataclass_json\n@dataclass\nclass Person:\n    name: str\n    age: int\n\n@dataclass_json(letter_case=LetterCase.CAMEL)\n@dataclass\nclass Product:\n    product_id: str\n    item_name: str\n\n# Basic usage\nperson = Person(name='Alice', age=30)\nprint(f\"To JSON: {person.to_json()}\")\nloaded_person = Person.from_json('{\"name\": \"Bob\", \"age\": 25}')\nprint(f\"From JSON: {loaded_person}\")\n\n# With camelCase conversion\nproduct = Product(product_id='P123', item_name='Laptop')\nprint(f\"Product to JSON (camelCase): {product.to_json()}\")\nloaded_product = Product.from_json('{\"productId\": \"P456\", \"itemName\": \"Mouse\"}')\nprint(f\"Product from JSON (camelCase): {loaded_product}\")","lang":"python","description":"This quickstart demonstrates the core functionality of `dataclasses-json` using the `@dataclass_json` decorator. It shows how to serialize dataclass instances to JSON strings and deserialize JSON strings back into dataclass instances. An example of converting field names to camelCase for JSON representation is also included."},"warnings":[{"fix":"Upgrade to v0.6.0 or higher. For complex Union types, ensure your data has sufficient information for `dataclasses-json` to infer the correct type, or provide custom decoding logic.","message":"Union type deserialization behavior changed significantly in v0.6.0. Earlier versions (pre-0.6.0) often struggled with correctly deserializing complex Union types, especially when nested within lists or dictionaries, or when a discriminating field was not present. v0.6.0 introduced automatic coercion of built-in types without exceptions, and subsequent versions (e.g., v0.6.1, v0.6.4) provided further fixes for Union deserialization logic.","severity":"breaking","affected_versions":"<0.6.0"},{"fix":"Review type hint usage for complexity. If encountering 'Unknown type' warnings with `from __future__ import annotations`, consider separating dataclass definitions into files without this import, or explicitly providing Marshmallow fields via `mm_field` metadata for problematic fields.","message":"Version 0.6.7 includes a warning about 'buggy type resolution'. This can manifest as unexpected deserialization behavior or warnings during schema generation, particularly when using advanced type hints or `from __future__ import annotations`, which can sometimes interfere with how `dataclasses-json` introspects types. Earlier issues reported 'Unknown type warning' for basic types like `int` under these conditions.","severity":"gotcha","affected_versions":">=0.6.7 and potentially earlier versions with `from __future__ import annotations`"},{"fix":"Always use timezone-aware `datetime` objects for predictable serialization/deserialization, or implement custom encoders/decoders (e.g., for ISO 8601 string format) if exact inverse behavior or specific timezone handling is required.","message":"When encoding/decoding `datetime` objects, `dataclasses-json` converts them to/from float timestamps. A significant caveat is that if a `datetime` object is timezone-naive during encoding, it will be assumed to be in the system's local timezone. Upon decoding, it will be converted into a timezone-aware object (also in the system's local timezone). This can lead to non-inverse behavior, where `obj.from_json(obj.to_json()) != obj` if the original object was naive.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Upgrade to v0.6.5 or a newer version to ensure proper deserialization of generic dataclasses.","message":"Generic dataclasses did not always deserialize correctly in older versions, often resulting in a dictionary instead of the intended generic dataclass instance. This was a known limitation that was addressed in v0.6.5.","severity":"gotcha","affected_versions":"<0.6.5"},{"fix":"Avoid overriding `__init__` directly. Instead, use `__post_init__` for post-initialization logic. If `__init__` must be overridden, ensure all dataclass fields are correctly initialized.","message":"Overriding the `__init__` method in a dataclass that uses `@dataclass_json` can interfere with the methods automatically generated by the `@dataclass` decorator (and by extension, `dataclasses-json`). This can lead to `AttributeError` for fields that are not properly initialized within the custom `__init__`.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-05-12T14:08:23.061Z","next_check":"2026-07-11T00:00:00.000Z","problems":[{"fix":"Provide a default value for the field in the dataclass (e.g., `field_name: Optional[str] = None`). Alternatively, if the field should genuinely be optional and infer `None` if missing, use `infer_missing=True` when calling `from_dict` or `from_json`. For example: `YourDataclass.from_json(json_string, infer_missing=True)`.","cause":"When deserializing JSON using `from_dict` or `from_json`, a required field (or an `Optional` field without a default value) is missing from the input JSON data. `dataclasses-json` attempts to access a key that does not exist in the deserialized dictionary.","error":"KeyError: 'field_name'"},{"fix":"Ensure the types in your JSON string precisely match the type hints in your dataclass. For missing required fields, provide them in the JSON string. If a field can be optional, define it as `Optional[Type]` and either provide `null` in the JSON or ensure `infer_missing=True` is used with `from_json`/`from_dict` (though `schema().loads` will still apply Marshmallow's validation rules).","cause":"When using `YourDataclass.schema().loads(json_string)` for deserialization, the input JSON data does not conform to the expected type or structure defined in the dataclass, or a required field is missing. This happens because `dataclasses-json` leverages Marshmallow for stricter schema validation when `.schema()` methods are invoked.","error":"marshmallow.exceptions.ValidationError: {'field_name': ['Invalid type.']}` or `marshmallow.exceptions.ValidationError: {'field_name': ['Missing data for required field.']}"},{"fix":"Always provide explicit type arguments for generic types. For example, change `field: tuple` to `field: Tuple[int, str]` or `field: tuple[int, str]` (using `from typing import Tuple` if on Python < 3.9).","cause":"This error occurs when a dataclass field is annotated with a generic type like `list` or `tuple` without specifying the element type (e.g., `field: tuple` instead of `field: Tuple[str, int]` or `field: tuple[str, int]` in Python 3.9+). `dataclasses-json` requires explicit type arguments for container types to correctly infer the schema for nested elements during deserialization.","error":"AttributeError: type object 'tuple' has no attribute '__args__'"},{"fix":"Ensure that the `@dataclass_json` decorator is applied *first*, followed by `@dataclass`. The correct order is:\n```python\nfrom dataclasses import dataclass\nfrom dataclasses_json import dataclass_json\n\n@dataclass_json\n@dataclass\nclass MyDataClass:\n    field_a: str\n    field_b: int\n```","cause":"This issue often arises when the `@dataclass_json` decorator is applied after `@dataclass` (e.g., `@dataclass @dataclass_json`), or when there's an interaction with other decorators or inheritance that modifies the `__init__` method in an unexpected way. The order of decorators can be crucial, as `dataclasses-json` often needs to preprocess the class before `@dataclass` generates its `__init__`.","error":"TypeError: __init__() got an unexpected keyword argument 'X'"}],"ecosystem":"pypi","meta_description":null,"install_score":100,"install_tag":"verified","quickstart_score":80,"quickstart_tag":"verified","pypi_latest":null,"install_checks":{"last_tested":"2026-05-12","tag":"verified","tag_description":"installs cleanly on critical runtimes, fast import, recently tested","results":[{"runtime":"python:3.10-alpine","python_version":"3.10","os_libc":"alpine (musl)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":0.2,"mem_mb":6.4,"disk_size":"19.4M"},{"runtime":"python:3.10-slim","python_version":"3.10","os_libc":"slim (glibc)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":0.14,"mem_mb":6.3,"disk_size":"20M"},{"runtime":"python:3.11-alpine","python_version":"3.11","os_libc":"alpine (musl)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":0.31,"mem_mb":7.2,"disk_size":"21.5M"},{"runtime":"python:3.11-slim","python_version":"3.11","os_libc":"slim (glibc)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":0.26,"mem_mb":7.2,"disk_size":"22M"},{"runtime":"python:3.12-alpine","python_version":"3.12","os_libc":"alpine (musl)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":0.26,"mem_mb":7.4,"disk_size":"13.3M"},{"runtime":"python:3.12-slim","python_version":"3.12","os_libc":"slim (glibc)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":0.26,"mem_mb":7.4,"disk_size":"14M"},{"runtime":"python:3.13-alpine","python_version":"3.13","os_libc":"alpine (musl)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":0.2,"mem_mb":6.7,"disk_size":"12.9M"},{"runtime":"python:3.13-slim","python_version":"3.13","os_libc":"slim (glibc)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":0.21,"mem_mb":6.7,"disk_size":"13M"},{"runtime":"python:3.9-alpine","python_version":"3.9","os_libc":"alpine (musl)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":0.17,"mem_mb":6,"disk_size":"18.9M"},{"runtime":"python:3.9-slim","python_version":"3.9","os_libc":"slim (glibc)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":0.14,"mem_mb":6,"disk_size":"19M"}]},"quickstart_checks":{"last_tested":"2026-04-23","tag":"verified","tag_description":"quickstart runs on critical runtimes, recently tested","results":[{"runtime":"python:3.10-alpine","exit_code":0},{"runtime":"python:3.10-slim","exit_code":0},{"runtime":"python:3.11-alpine","exit_code":0},{"runtime":"python:3.11-slim","exit_code":0},{"runtime":"python:3.12-alpine","exit_code":0},{"runtime":"python:3.12-slim","exit_code":0},{"runtime":"python:3.13-alpine","exit_code":0},{"runtime":"python:3.13-slim","exit_code":0},{"runtime":"python:3.9-alpine","exit_code":0},{"runtime":"python:3.9-slim","exit_code":0}]}}