Skip to main content

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

typehintjson-1.0.2.tar.gz (3.1 kB view details)

Uploaded Source

Built Distribution

typehintjson-1.0.2-py3-none-any.whl (3.8 kB view details)

Uploaded Python 3

File details

Details for the file typehintjson-1.0.2.tar.gz.

File metadata

  • Download URL: typehintjson-1.0.2.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

Hashes for typehintjson-1.0.2.tar.gz
Algorithm Hash digest
SHA256 01ec9714a4fe97cc3d41db6392e77579f9a81b08b91ea3fdfa111f66a31d1638
MD5 05145a1a06a392e1b00844b5ff5d9f54
BLAKE2b-256 11df5c4e485a258e4b975de4a7fee8b390cd5de5daa18c1581fed285c6e31a38

See more details on using hashes here.

File details

Details for the file typehintjson-1.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for typehintjson-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 81403049090adf89f35903a5abe68bc39d92259a9a52b13a042a01eab2be8e01
MD5 6f2c2449ea23642b0966398c4d60a4a8
BLAKE2b-256 ef1aa2ce85f6aa777de0e4bbf5cf1122fa825aed9557f236edcaf672cc6a8267

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page