Converts dataclasses / enums to JSON and back using type hints
Project description
JSON Decoder / Encoder for type hints
Simple, 2 file python module that parses JSON into dataclasses / enums and vice versa. Ignores extra fields, and works with default values for missing fields.
Requires Python 3.8.0 or higher
For security sake, you have to know the type you're expecting to deserialize into.
Unions will be resolved in order (i.e. Union[int, MyType, None] will first try parsing as int, then as MyType, then as None), so if a value is MULTIPLE valid types, it might not pick the right one.
Installation
pip install typehintjson
Usage
import json
import typing as T
from typehintjson import parse_as_type, dataclass_to_dictionary
from dataclasses import dataclass
@dataclass
class Child:
x: T.Union[int, str]
y: int = 4
@dataclass
class Parent:
a: int
c: Child
obj = Parent(a=2, c=Child(x="meow"))
print(repr(parse_as_type(json.loads(json.dumps(dataclass_to_dictionary(obj))), Parent)))
# Parent(a=2, c=Child(x='meow', y=4))
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file typehintjson-1.0.0.tar.gz
.
File metadata
- Download URL: typehintjson-1.0.0.tar.gz
- Upload date:
- Size: 3.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.10.4
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9b9d44a111705e2e51b8397741335c559b7c71be9bea1026b290edd42d6b30fe |
|
MD5 | 0a505916c2428f7e9b916b57eee135a0 |
|
BLAKE2b-256 | 8de6166088ceb7ac69911c746e3ef29711d905fb4e49a79627d7db6113880943 |
File details
Details for the file typehintjson-1.0.0-py3-none-any.whl
.
File metadata
- Download URL: typehintjson-1.0.0-py3-none-any.whl
- Upload date:
- Size: 3.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.10.4
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | cd1aa2a369ee170ca962e6474084f1b6c14166d50458f7d60dc0311955f9f9ae |
|
MD5 | e665f94882da0568167952b14255326f |
|
BLAKE2b-256 | ce48df839a9d1e602be0cc5b0274905adaa127ac280bf9fa5fc209af2e1af03c |