JSON decoding for Python with type hinting (PEP 484)
Project description
typedjson
JSON decoding for Python with type hinting (PEP 484).
Requirements
- Python >= 3.7
- Use
from __future__ import annotations
(See PEP 563). - Use non-generic
@dataclasses.dataclass
without modifying__init__
to decode JSON as class.
Features
- Support decoding types as below:
- primitive types like
str
,int
,float
,bool
andNone
. -Union
andOptional
. - homogeneous and heterogeneous
Tuple
- variable-length
Tuple
. - non-generic dataclasses.
- primitive types like
- Support API like
json.load
andjson.loads
.
Example
from __future__ import annotations
from typing import Optional
import typedjson
from dataclasses import dataclass
@dataclass(frozen=True)
class NameJson:
first: str
last: Optional[str]
@dataclass(frozen=True)
class CatJson:
id: str
age: int
name: Optional[NameJson]
json = {
'id': 'test-cat',
'age': 13,
'name': {
'first': 'Jiji',
},
}
print(typedjson.decode(CatJson, json)) # Output: CatJson(id='test-cat', age=13, name=NameJson(first='Jiji', last=None))
print(typedjson.decode(CatJson, {})) # Output: <DecodingError path=('id',)>
Please refer to test codes for more detail.
TODO
- Use
__init__.__annotation__
to decode JSON as arbitrary class.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
typedjson-0.2.0.tar.gz
(3.2 kB
view hashes)