python - 从 json 创建 python 对象
问题描述
我有包含此类信息的 json 文件
{
"cars" : [{
"model" : " BMW",
"gas" : 100,
},
{
"model" : "LADA",
"gas" : 150
},
{
"model" : "SUZUKI",
"gas" : 70
}]
}
和下课
class GasCar(Car):
def __init__(self, model=None, gas=None):
super(GasCar, self).__init__()
self.gas = gas
self.model = model
如何创建类对象并将数据从 json 传输到类实例?
我试过这个
car = GasCar()
s = json.dumps(car)
s = json.dumps(car.__dict__)
解决方案
您的 JSON 无法被 pythonjson
模块解析,因为如果您想解决这个问题,100,
您可以参考这个答案。但是假设json如下:
import json
class GasCar():
def __init__(self, model=None, gas=None):
super(GasCar, self).__init__()
self.gas = gas
self.model = model
cars = """{
"cars" : [{
"model" : "BMW",
"gas" : 100
},
{
"model" : "LADA",
"gas" : 150
},
{
"model" : "SUZUKI",
"gas" : 70
}]
}"""
json_cars = json.loads(cars)
cars = json_cars["cars"] # gets "cars" list
您可以像这样创建汽车对象:
car_object1 = GasCar(cars[0]["model"], cars[0]["gas"])
print(car_object1.model) # prints "BMW"
或者,如果您想要所有汽车的列表:
car_objects = [GasCar(car["model"], car["gas"]) for car in cars]
推荐阅读
- algorithm - 图中的负循环和正循环是什么?
- wso2 - WSO2 API Analytics - 如何故意调用异常请求模式
- firebase - 如何在 Kotlin Android 的 Recycler View 中修复这个问题
- html - [HTML]:带有身份验证的视频标签
- r - 在ggplot中拟合一条对角线以绘制图形
- flutter - 在颤动中拖动旋转的容器
- node.js - 使用 mongoose-multi 和 gridfs 流保存新集合中的数据不起作用?
- spring-boot - 在 JmsOutBoundGatway 中为重新连接尝试添加固定退避
- r - R中的时间序列预测;绘制“事件”并在初始预测后生成具有指定日期范围的新预测图
- jquery - jQuery 函数在移动设备上不起作用