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

Uploaded Source

Built Distribution

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

Uploaded Python 3

File details

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

File metadata

  • Download URL: typehintjson-1.0.3.tar.gz
  • Upload date:
  • Size: 3.2 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.3.tar.gz
Algorithm Hash digest
SHA256 4499bc19d290d1489279043cf1d532b5a44a4816de7d6c47ead31c50b1e4e046
MD5 2a72deb8f0e56ed1b2fa5718b3a6f288
BLAKE2b-256 bac7e6e9fc3c7acca30d3ec215fd390e35b8aed96a0d637c98cf6c692297fbe7

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for typehintjson-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 685a8fede41d6f194a1c7c67ed4cf60bf168fbb62b0c56627bd3310aaab2f8b0
MD5 87b63e57ea996c376d67fe4c9088cddf
BLAKE2b-256 60bc4e7c91be5f07998fddc7bfcd10040cb0d38e0d50ef380e8f813aeebab46c

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