コード例 #1
0

@dataclass
class Movie:
    name: str
    year: int
    rating: Rating = jsonfield(serializer_class=RatingSerializer)


movie = Movie("Terminator: Dark Fate", 2019, Rating(5, 100))
json_str = to_json(movie)
print(json_str)
# {"name": "Terminator: Dark Fate", "year": 2019, "rating": [5, 100]}

json_str = '{"name": "Terminator: Dark Fate", "year": 2019, "rating": [5, 100]}'
movie = from_json(json_str, Movie)
print(movie)
# Movie(name='Terminator: Dark Fate', year=2019, rating=Rating(rating=5, vote_count=100))


class UpperStringSerializer(Serializer[str]):
    def serialize(self, data: str) -> str:
        return data.upper()

    def deserialize(self, data: str, type_: Type[str]) -> str:
        return data.upper()


@dataclass
class Movie:
    name: str
コード例 #2
0
from dataclasses import dataclass
from jsondataclass import from_json, to_json


@dataclass
class ContactInfo:
    email: str
    phone_number: str


@dataclass
class User:
    id: int
    name: str
    info: ContactInfo


user = User(1, "John Doe", ContactInfo("*****@*****.**", "+19999999"))
print(to_json(user))
# {"id": 1, "name": "John Doe", "info": {"email": "*****@*****.**", "phone_number": "+19999999"}}

json_str = '{"id": 1, "name": "John Doe", "info": {"email": "*****@*****.**", "phone_number": "+19999999"}}'
print(from_json(json_str, User))
# User(id=1, name='John Doe', info=ContactInfo(email='*****@*****.**', phone_number='+19999999'))
コード例 #3
0
from dataclasses import dataclass
from typing import Literal

from jsondataclass import from_json, to_json


@dataclass
class Movie:
    name: str
    year: int
    rating: Literal[1, 2, 3, 4, 5]


movie = Movie("Terminator: Dark Fate", 2019, 5)
print(to_json(movie))
# > {"name": "Terminator: Dark Fate", "year": 2019, "rating": 5}

json_str = '{"name": "Terminator: Dark Fate", "year": 2019, "rating": 5}'
print(from_json(json_str, Movie))
# > Movie(name='Terminator: Dark Fate', year=2019, rating=5)
コード例 #4
0
ファイル: timestamp.py プロジェクト: tushkanin/jsondataclass
from jsondataclass import from_json, to_json, jsonfield


@dataclass
class User:
    id: int
    name: str
    last_login: datetime.timestamp


user = User(1, "John Doe", datetime.now())
json_str = to_json(user)
print(json_str)
# {"id": 1, "name": "John Doe", "last_login": 1572541610}

user = from_json(json_str, User)
print(user)
# User(id=1, name='John Doe', last_login=datetime.datetime(2019, 10, 31, 19, 7, 41))


@dataclass
class User:
    id: int
    name: str
    last_login: datetime.timestamp = jsonfield(
        serializer_kwargs={"timezone": timezone.utc})


user = User(1, "John Doe", datetime.now())
json_str = to_json(user)
print(json_str)