Reputation: 36
So I have a JSON file
{
"Vehicles": [
{
"Name": "Car",
"ID": 1
},
{
"Name": "Plane",
"ID": 2
}
]
}
and I created the class in python
class vehicleclass:
def __init__(self, vname, vid):
self.name = vname
self.id = vid
what I would like to do is create an instance of the object vehicles for each vehicle in the JSON, I am reading from the file as shown here
with open('vehicle.json') as json_file:
data = json.load(json_file)
I then run this piece of code
for each in data['Vehicles']:
how do I create an instance of vehicleclass using each 'name' iteration in the JSON file
note I realize I can get the value for each 'name' by calling each['Name']
in the for loop
Upvotes: 0
Views: 207
Reputation: 6234
from what I understand I think this should achieve it.
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"]
]
Upvotes: 1