Skip to content

Instantly share code, notes, and snippets.

@yzhong52
Created September 8, 2021 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yzhong52/4d699f6982e0538fd1bcf54f08c22863 to your computer and use it in GitHub Desktop.
Save yzhong52/4d699f6982e0538fd1bcf54f08c22863 to your computer and use it in GitHub Desktop.
Serialize and Deserialize complex JSON in Python
from typing import List
import json
class Student(object):
def __init__(self, first_name: str, last_name: str):
self.first_name = first_name
self.last_name = last_name
@classmethod
def from_json(cls, data):
return cls(**data)
class Team(object):
def __init__(self, students: List[Student]):
self.students = students
@classmethod
def from_json(cls, data):
students = list(map(Student.from_json, data["students"]))
return cls(students)
student1 = Student(first_name="Jake", last_name="Foo")
student2 = Student(first_name="Jason", last_name="Bar")
team = Team(students=[student1, student2])
# Serializing
data = json.dumps(team, default=lambda o: o.__dict__, sort_keys=True, indent=4)
print(data)
# Deserializing
decoded_team = Team.from_json(json.loads(data))
print(decoded_team)
print(decoded_team.students)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment