[Convert] Json & Object

Rmag Breaking News
from dataclasses import dataclass
from typing import TypedDict

class StudentDict(TypedDict):
Name: str
Old: int

@dataclass
class Student:
name: str
old: int

def encode(self) -> StudentDict:
return StudentDict(Name=self.name, Old=self.old)

@classmethod
def decode(cls, student: StudentDict) -> “Student”:
return cls(name=student[“Name”], old=student[“Old”])

def main():
student = Student(name=”John”, old=20)
print(student.encode())
print(Student.decode(student.encode()))

if __name__ == “__main__”:
main()

Leave a Reply

Your email address will not be published. Required fields are marked *