Load and dump data from json-like format into typed data structures
Maintained. Last release 6 months ago. Weaker on release cadence.
pip install typedloadtypedload
Load and dump json-like data into typed data structures in Python3, enforcing a schema on the data.
This module provides an API to load dictionaries and lists (usually loaded from json) into Python's NamedTuples, dataclass, sets, enums, and various other typed data structures; respecting all the type-hints and performing type checks or casts when needed.
It can also dump from typed data structures to json-like dictionaries and lists.
It is very useful for projects that use Mypy and deal with untyped data like json, because it guarantees that the data will follow the specified schema.
It is released with a GPLv3 license but it is possible to ask for LGPLv3.

Example
For example this dictionary, loaded from a json:
data = {
'users': [
{
'username': 'salvo',
'shell': 'bash',
'sessions': ['pts/4', 'tty7', 'pts/6']
},
{
'username': 'lop'
}
],
}
Can be treated more easily if loaded into this type:
@dataclasses.dataclass
class User:
username: str
shell: str = 'bash'
sessions: list[str] = dataclasses.field(default_factory=list)
class Logins(NamedTuple):
users: list[User]
And the data can be loaded into the structure with this:
t_data = typedload.load(data, Logins)
And then converted back:
data = typedload.dump(t_data)
Supported types
Since this is not magic, not all types are supported.
The following things are supported:
- Basic python types (int, str, bool, float, NoneType)
- NamedTuple
- Enum
- Optional[SomeType]
- list[SomeType]
- dict[TypeA, TypeB]
- tuple[TypeA, TypeB, TypeC] and tuple[SomeType, ...]
- set[SomeType]
- TypeA | TypeB
- dataclass
- attr.s
- ForwardRef (Refer to the type in its own definition)
- Literal
- TypedDict
- datetime.date, datetime.time, datetime.datetime
- re.Pattern