python - 如何将 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"
}
]
解决方案
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]
推荐阅读
- domain-driven-design - 订阅是遵循 ddd 原则的域的一部分吗?
- ros - 离线安装 ROS Melodic
- javascript - 如何创建 javascript 数组并将另一个数组数据保存到 Javascript 中创建的数组
- elasticsearch - 发送脚本调用请求时,将 Data Raw 内容移动到 URL
- cakephp - CakePHP 4 - 自定义请求和响应格式
- hadoop - 辅助名称节点无法启动 ssh:连接到主机 0.0.0.7 端口 22:连接超时
- java - API 30 中的透明状态栏
- .net - 获取 IISAppPool | .NET 中的选择对象状态为空
- date - 具有短时区 ID 的 hive 时区转换
- sql - 两个选择结果的计算(乘法)