我有一个数据类数组,我需要序列化为 JSON。我将列表包装在一个类中 (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")
我可以以某种方式摆脱包装类并仍然轻松序列化List[Person]
吗?
最佳答案
您可以使用 json.dumps
函数的 default
参数并传递函数 attrs.asdict
来序列化它。
我添加了“persons”键,以便它与您的代码输出相匹配。
import json
import attrs
@attrs.frozen
class Person:
name: str
age: int
grades: dict[str, int]
def run(filename: str) -> None:
college = []
college.append(Person("uzi", 51, {"math": 100, "cs": 90}))
college.append(Person("dave", 76, {"math": 94, "music": 92}))
college.append(Person("dan", 22, {"bible": 98}))
with open(filename, "w+") as fl:
fl.write(
f"{json.dumps({'persons': college}, default=attrs.asdict, indent=4)}\n"
)
run("my_json.json")
输出
{
"persons": [
{
"name": "uzi",
"age": 51,
"grades": {
"math": 100,
"cs": 90
}
},
{
"name": "dave",
"age": 76,
"grades": {
"math": 94,
"music": 92
}
},
{
"name": "dan",
"age": 22,
"grades": {
"bible": 98
}
}
]
}
关于python - 将数据类数组序列化为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71844113/