首页 > 解决方案 > 为 json 中的实例创建对象

问题描述

所以我有一个 JSON 文件

{
  "Vehicles": [
    {
      "Name": "Car",
      "ID": 1
    },
    {
      "Name": "Plane",
      "ID": 2
    }
  ]
}

我在python中创建了这个类

class vehicleclass: 
    def __init__(self, vname, vid):
        self.name = vname
        self.id = vid

我想做的是在 JSON 中为每辆车创建一个对象车辆的实例,我正在从文件中读取,如下所示

with open('vehicle.json') as json_file:
        data = json.load(json_file)

然后我运行这段代码

for each in data['Vehicles']:

如何使用 JSON 文件中的每个“名称”迭代创建车辆类的实例

each['Name']注意我意识到我可以通过调用for 循环来获取每个“名称”的值

标签: pythonjsonpython-3.xclasspython-3.8

解决方案


据我了解,我认为这应该实现它。

with open("vehicle.json") as json_file:  # opens your vehicles.json file

    # this will load your file object into json module giving you a dictionary if its a valid json
    data = json.load(json_file)

    # this list comprehension uses data dictionary to generate your vehicleclass instances
    vehicle_instances = [
        vehicleclass(vehicle["Name"], vehicle["ID"]) for vehicle in data["Vehicles"]
    ]

推荐阅读