首页 > 解决方案 > 从 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__)

标签: pythonjson

解决方案


您的 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]

推荐阅读