所以我有一个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 文件中的每个"名称"迭代创建车辆类的实例
注意我意识到我可以通过在 for 循环中调用each['Name']
来获取每个"名称"的值
据我所知,我认为这应该可以实现它。
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"]
]