JSON decoding for Python with type hinting (PEP 484).
- Python >= 3.7
- Mypy <= 0.770
- Use non-generic or parameterized class to decode JSON.
- Use type hints without forward references.
- Support decoding types as below:
- primitive types like
str
,int
,float
,bool
andNone
. Union
andOptional
.- homogeneous and heterogeneous
Tuple
andList
. - variable-length
Tuple
. - non-generic and parameterized dataclasses.
- primitive types like
- Support API like
json.load
andjson.loads
.
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(TypeMismatch(('id',)))
Please refer to test codes for more detail.
Please read CONTRIBUTING.md.
- Prohibit decoding
Set
andDict
explicitly. - Provide the API document.
- Explain why typedjson uses undocumented APIs.
- Explain what typedjson resolves.
- Improve API to dump like
json.dump
andjson.dumps
.- Provide mypy plugin to check whether the class is encodable as JSON or not with
@typedjson.encodable
decorator.
- Provide mypy plugin to check whether the class is encodable as JSON or not with
- Improve the peformance of
typedjson.decode
. - Support type hints with forward reference.
- Support
TypedDict
.