Marshal/unmarshal attrs-based data classes to and from JSON
Project description
fieldmarshal – marshal/unmarshal attrs-based data classes to and from JSON
Note: This is module is still in development - APIs might change in backwards-incompatible ways.
Example
>>> from fieldmarshal import struct, field, marshal, unmarshal >>> from typing import List, Set >>> @struct ... class Post: ... title: str ... tags: Set[str] ... >>> @struct ... class User: ... id: int ... name: str ... posts: List[Post] ... is_admin: bool = field("is-admin", default=False) ... >>> fred = User(1, "fred", [Post("hello world!", tags={"a", "b"})]) >>> data = marshal(fred) >>> data {'id': 1, 'name': 'fred', 'posts': [{'title': 'hello world!', 'tags': ['a', 'b']}], 'is-admin': False} >>> assert unmarshal(data, User) == fred >>>
The struct
and field
helpers are just convenience wrappers around attr.s
and attr.ib
. The equivalent code with attrs
is:
>>> import attr >>> from fieldmarshal import Options >>> @attr.s(slots=True, auto_attribs=True) ... class User: ... # ... ... is_admin: bool = attr.ib( ... default=False, ... metadata={'fieldmarshal': Options(name="is-admin")}, ... ) >>>
This module provides marshalling/unmarshalling (or serialization/deserialization) of attrs-based "data classes" from and to JSON.
It is inspired by Go's json.Marshal/json.Unmarshal
and cattrs.
The main goal is to make it easy to quickly build useful (partial) class
representations for real-world JSON data, such as those received from HTTP APIs
(See the examples
subdirectory), and to allow efficient
marshalling/unmarshalling to and from JSON.
Features:
- Support for renaming fields (see Example above).
- Unknown/extra JSON keys are ignored by default.
- Hook system to customize marshalling/unmarshalling of custom or complex
types (e.g.
Union
s) - Built-in handling of common cases, such as
Enums
, simpleUnion
s. - Limited support for non-string dict keys (bool, int, float, Enum).
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Filename, size | File type | Python version | Upload date | Hashes |
---|---|---|---|---|
Filename, size fieldmarshal-0.0.1-py3-none-any.whl (7.4 kB) | File type Wheel | Python version py3 | Upload date | Hashes View |
Filename, size fieldmarshal-0.0.1.tar.gz (13.2 kB) | File type Source | Python version None | Upload date | Hashes View |
Hashes for fieldmarshal-0.0.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 79afadcae34bc9c2a1b38c9e2900fd555b6df98bf4945cbff6b7423d4f8213db |
|
MD5 | f6e13948f73c27224d3542024584f749 |
|
BLAKE2-256 | eeb4591a2622cac93c2ff410d0e50797149b2e82f49853afc83c514b266eaa87 |