I want to parse flight data from Aviationstack API.
For this example, I format the URL to get data from flight with departure at Marseille airport (France) with the parameter dep_icao=LFML
(cf. documentation) :
# get data for flights from Marseille airport
url = 'http://api.aviationstack.com/v1/flights?access_key=MYAPIKEY&dep_icao=LFML'
req = requests.get(url)
response = req.json()
This is the response (shortened)
{'pagination': {'limit': 100, 'offset': 0, 'count': 100, 'total': 377},
'data': [{'flight_date': '2022-12-24',
'flight_status': 'active',
'departure': {'airport': 'Marseille Provence Airport',
'timezone': 'Europe/Paris',
'iata': 'MRS',
'icao': 'LFML',
'terminal': '1A',
'gate': None,
'delay': 10,
'scheduled': '2022-12-24T09:00:00 00:00',
'estimated': '2022-12-24T09:00:00 00:00',
'actual': '2022-12-24T09:09:00 00:00',
'estimated_runway': '2022-12-24T09:09:00 00:00',
'actual_runway': '2022-12-24T09:09:00 00:00'},
'arrival': {'airport': 'El Prat De Llobregat',
'timezone': 'Europe/Madrid',
'iata': 'BCN',
'icao': 'LEBL',
'terminal': '1',
'gate': None,
'baggage': '06',
'delay': None,
'scheduled': '2022-12-24T10:05:00 00:00',
'estimated': '2022-12-24T10:05:00 00:00',
'actual': None,
'estimated_runway': None,
'actual_runway': None},
'airline': {'name': 'Qatar Airways', 'iata': 'QR', 'icao': 'QTR'},
'flight': {'number': '3721',
'iata': 'QR3721',
'icao': 'QTR3721',
'codeshared': {'airline_name': 'vueling',
'airline_iata': 'vy',
'airline_icao': 'vlg',
'flight_number': '1509',
'flight_iata': 'vy1509',
'flight_icao': 'vlg1509'}},
'aircraft': None,
'live': None},
[...]
}]}
Then I want to iterate through this JSON response. I can get the pagination
info right but I'm only able to get info from the first element in data
, so I will later loop through all results.
My problem is that I would only like to get the iata
item nested in flight
. The way I'm trying to get it returns 'dict' object is not callable
error.
# iterate through JSON response
pagination_data = response.get("pagination")
flight_data = response.get("data")[0]
total_results = pagination_data.get("total")
flight = flight_data.get('flight')('iata')
pprint(f"total results : {total_results}")
pprint(f"flight : {flight}")
CodePudding user response:
The get method will return a dictionnary which is not function and then can not be called
It should be flight = flight_data.get('flight').get('iata')
Alternatives :
(but without returning None) flight_data.get('flight')['iata']
(but without returning None) flight=flight_data['flight']['iata']