python - 将数据类数组序列化为 JSON

标签 python json serialization python-attrs

我有一个数据类数组,我需要序列化为 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/

相关文章:

javascript - 将变量从 python 传递到 javascript

python - Django QuerySet 不可序列化

java - 如何手动序列化一个类?

python - Pandas Dataframe 只返回第一行 JSON 数据

android - 设计 "Platform-Independent"GWT 服务器的最佳方法是什么?

python - 使用 PyCharm 进行 pytorch 调试超时

Python IRC Bot 链接解析器?

python - 如何在 replit 上运行音乐机器人 (discord.py)

java - 使用 GSON 将多个 Collection<String> 合并为一个 JSON String

java - 使用 jackson 转换带有重复键的 JSON