Typed JSON dataclasses
Project description
python-jsondataclasses
Typed JSON dataclasses for Python 3.9+
Installation
Installation is done purely via git, as this package is not published on PyPI
pip install git+https://github.com/issy/python-jsondataclasses
Usage
from datetime import date
from typing import Literal, Optional
from jsondataclasses import jsondataclass, jsonfield
def parse_date(date_string: str) -> date:
return date.fromisoformat(date_string.replace(".", "-"))
@jsondataclass
class Car:
make: Literal["Ford", "Renault", "Volkswagen"] = jsonfield("carMake")
model: str = jsonfield("model")
manufactured_at: date = jsonfield("dateOfManufacture", parse_date)
num_of_wheels: Optional[int] = jsonfield("numberOfWheels", default_value=4)
car = Car({
"carMake": "Ford",
"model": "Focus",
"dateOfManufacture": "2018.03.14"
})
print(car) # Car(make='Ford', model='Focus', manufactured_at=datetime.date(2018, 3, 14), num_of_wheels=4)
Class field types can be any primitive type (eg. str
, int
, datetime
), a variadic generic (eg. list[str]
, Optional[int]
, Literal["hello", "world"]
). The default_value
argument of jsonfield
will be used if the key is not found in the json structure, the type of the class field is not Optional[...]
. In this case, the value of default_value
will be passed to the supplied parser function.
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
jsondataclasses-0.0.3.tar.gz
(3.7 kB
view hashes)
Built Distribution
Close
Hashes for jsondataclasses-0.0.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | ee83d83bf51663a4c5090e96f04ca89392e1fd28aa34a77538797ab8082b36e1 |
|
MD5 | 07ede4902565a796884755d1ed9083ad |
|
BLAKE2b-256 | 6c188e70e623712f03939a61462bee6ca8b6b4b225f6566c0e01e98a60a4586e |