Reputation: 1100
i need to create an array like this,
{
"driver_details":[
{
"dr_id": 1,
"v_id": 2,
"v_type":"car",
"condition":"ok"
},
{
"dr_id": 2,
"v_id": 3,
"v_type":"cab",
"condition":"ok"
},
]
}
I tried with this method which returns dr_id
, v_id
, condition
, type
values as list,
But extracting values from it is difficult and cannot get specific data like dr_id
,v_id
.
def get(self, owId):
return_data = []
for driver in driver_schema.dump(DriverModel().get_driversby_ownerId(owId)):
for vehicle in vehicle_schema.dump(VehicleModel().vehicle_detailby_driver(driver['dr_id'])):
return_data.append(driver['dr_id'])
return_data.append(vehicle['vehicle_type'])
return_data.append(vehicle['condition'])
return return_data
So I tried with json.dump()
method but it returns the following value
"[1.0, \"car\", false, 13.0, false, 2.0, \"bus\", false, 50.0, false]"
and also i tried with dictionary inside the loop like following
def get(self, owId):
return_data = {}
for driver in driver_schema.dump(DriverModel().get_driversby_ownerId(owId)):
for vehicle in vehicle_schema.dump(VehicleModel().vehicle_detailby_driver(driver['dr_id'])):
return_data.update({'driver':driver['dr_id'], 'vehicle':vehicle['vehicle_type'], 'v_type':vehicle['vehicle_type']})
return return_data
in this way, it only contains the last value from the loop.
So how can I achieve my expected results?
Thanks in advance.
Upvotes: 0
Views: 85
Reputation: 306
You are able to see only the last value because you are modifying on the same dictionary (update) again and again . Instead you can add those dictionary values to the list .
def get(self, owId):
return_data = []
for driver in driver_schema.dump(DriverModel().get_driversby_ownerId(owId)):
for vehicle in vehicle_schema.dump(VehicleModel().vehicle_detailby_driver(driver['dr_id'])):
return_data.append({'driver':driver['dr_id'], 'vehicle':vehicle['vehicle_type'], 'v_type':vehicle['vehicle_type']})
return return_data
After that you will be able to create a json with json.dumps().
Upvotes: 2
Reputation: 1383
Prepare a list of all driver and then map it with driver_details
key in dict and return that dict.
def get(self, owId):
driver_details = []
for driver in driver_schema.dump(DriverModel().get_driversby_ownerId(owId)):
for vehicle in vehicle_schema.dump(VehicleModel().vehicle_detailby_driver(driver['dr_id'])):
driver_details.append({
'driver': driver['dr_id'],
'vehicle': vehicle['vehicle_type'],
'v_type': vehicle['vehicle_type']
})
return {'driver_details': driver_details}
Upvotes: 2