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.1.tar.gz (3.1 kB view details)

Uploaded Source

Built Distribution

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

Uploaded Python 3

File details

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

File metadata

  • Download URL: typehintjson-1.0.1.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.1.tar.gz
Algorithm Hash digest
SHA256 b2391c417c9791a8f35d727266e54bece06b451929a95462a9619d5c094b818a
MD5 fd8a0fd8af07b0e6d1b9f046524be97c
BLAKE2b-256 61485d15f2262f931bb5819546a7c38af72c75b763c10069f2243cb6501b6d67

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for typehintjson-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 48e4c77e07d385d6ff2f142cfbd3b54296ea18291c84e598f6d0e6ad8572fad1
MD5 435c5174e0ea12f8b6dca42115e72975
BLAKE2b-256 477e37e60282aa2e835cb099b66ac5ceb0787a78c1708062cca8eb2313cc10b9

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