为 json 中的实例创建对象
Creating a object for instances in a json
所以我有一个 JSON 文件
{
"Vehicles": [
{
"Name": "Car",
"ID": 1
},
{
"Name": "Plane",
"ID": 2
}
]
}
我在 python
中创建了 class
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 文件
中的每个 'name' 迭代创建一个 vehicleclass 实例
注意我意识到我可以通过在 for 循环
中调用 each['Name']
来获取每个 '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"]
]
所以我有一个 JSON 文件
{
"Vehicles": [
{
"Name": "Car",
"ID": 1
},
{
"Name": "Plane",
"ID": 2
}
]
}
我在 python
中创建了 classclass 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 文件
中的每个 'name' 迭代创建一个 vehicleclass 实例注意我意识到我可以通过在 for 循环
中调用each['Name']
来获取每个 '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"]
]