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.4.tar.gz
.
File metadata
- Download URL: typehintjson-1.0.4.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 | f77ad97c2bbccbcd002ce7a51555f76528bc542d9292e702662a3feb64a6b7c0 |
|
MD5 | 27a48767e3a00a53c403ab92c831361b |
|
BLAKE2b-256 | 84a02c3dd196bfa19f4b2c62d08634adb5ffe2aada71dff3914a4c7ee41748ee |
File details
Details for the file typehintjson-1.0.4-py3-none-any.whl
.
File metadata
- Download URL: typehintjson-1.0.4-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 | 8599b9c96aa00dcdfe554cc37c24c63e5bddca87388466c86fc28da073e1909a |
|
MD5 | dd91a41c35ae12bd1ce6695f96fb3117 |
|
BLAKE2b-256 | 59c1ebd3acd286c0cc335d22e92bc16f11a63851b4309356022eb8869732407d |