I have an array of data classes I need to serialize to JSON. I wrap the list in a class (Persons)
@attrs.frozen
class Person:
name: str
age: int
grades: Dict[str, int]
@attrs.define
class Persons:
persons: List[Person] = attrs.field(factory=list)
def add(self, person: Person) -> None:
self.persons.append(person)
def run(filename: str) -> None:
college = Persons()
college.add(Person("uzi" , 51, {"math": 100, "cs": 90}))
college.add(Person("dave", 76, {"math": 94, "music": 92}))
college.add(Person("dan", 22, {"bible": 98}))
with open(filename, "w+") as fl:
fl.write(f"{json.dumps(attrs.asdict(college), indent=4)}\n")
Can I somehow get rid of the wrapping class and still serialize a List[Person] easily?
You can use
defaultargument of thejson.dumpsfunction and pass the functionattrs.asdictto serialize it.I have added the "persons" key so it matches the output of your code.
Output