首页 > 解决方案 > 如何将 JSON 转换为自定义类的实例?

问题描述

我不确定之前是否有人问过这个问题,但我找不到相关的自定义映射。通常它是直接的 JSON 到对象的 1:1 映射。

所以这是我的示例:

class Test():
    id: str
    name: str
    msg: str

data = [
    {
        "id": "12345",
        "client": "test",
        "msg": "random"
    }, {
        "id": "54321",
        "client": "test-2",
        "msg": "random-2"
    }
]

所以在上面我有一个 JSON,我想直接将它转换为我在第一堂课上的对象。请注意 JSON 中的“客户端”变为name.

所以当我加载它会变成的对象时的最终输出。

data = [
    {
        "id": "12345",
        "name": "test",
        "msg": "random"
    }, {
        "id": "54321",
        "name": "test-2",
        "msg": "random-2"
    }
]

标签: pythonjsonclass

解决方案


class Test():
    def __init__(self, id, client, msg):
        self.id = id
        self.name = client
        self.msg = msg

data = [
    {
        "id": "12345",
        "client": "test",
        "msg": "random"
    }, {
        "id": "54321",
        "client": "test-2",
        "msg": "random-2"
    }
]

# unpack values from dict and pass in as arguments for Test.__init__()
objects = [Test(**item) for item in data] 

推荐阅读