【问题标题】:KeyError when parsing JSON from API从 API 解析 JSON 时出现 KeyError
【发布时间】:2020-09-02 08:26:01
【问题描述】:

我需要从 API 请求的 JSON 文件中解析数据。 API 文档提供了如何实现它的示例代码,但是他们的方法会导致以下 KeyError:

Traceback (most recent call last):
  File "testing2.py", line 11, in <module>
    for flight in api_response['results']:
KeyError: 'results'

我花了很多时间寻找可能的原因,但找不到适合我的解决方案。 Python 文件如下所示:

import requests

params = {
  'access_key': my_access_key'
}

results = requests.get('http://api.aviationstack.com/v1/flights?access_key=my_access_key&airline_name=Air%20India&flight_number=560')

api_response = results.json()

for flight in api_response['results']:
    if (flight['live']['is_ground'] is False):
        print(u'%s flight %s from %s (%s) to %s (%s) is in the air.' % (
            flight['airline']['name'],
            flight['flight']['iata'],
            flight['departure']['airport'],
            flight['departure']['iata'],
            flight['arrival']['airport'],
            flight['arrival']['iata']))

我已经能够使用print(api_response) 读取数据,但是我无法解析其中的任何一个,因为关键的“结果”似乎根本不存在。

编辑:

这是直接转到 URL 或 print(api_response) 的结果,一大块文本:

{"分页":{"limit":100,"offset":0,"count":4,"total":4},"data":[{"flight_date":"2020-09-02 ","flight_status":"landed","departure":{"airport":"Indira Gandhi International","timezone":"Asia/Kolkata","iata":"DEL","icao":"VIDP" ,"终端":"3","门":"33","延迟":4,"预定":"2020-09-02T07:15:00+00:00","估计":"2020- 09-02T07:15:00+00:00","实际":"2020-09-02T07:18:00+00:00","estimated_runway":"2020-09-02T07:18:00+00: 00","actual_runway":"2020-09-02T07:18:00+00:00"},"arrival":{"airport":"Hyderabad Airport","timezone":"Asia/Kolkata","iata ":"HYD","icao":"VOHS","terminal":"1","gate":null,"baggage":null,"delay":2,"scheduled":"2020-09-02T09 :10:00+00:00","估计":"2020-09-02T09:10:00+00:00","实际":"2020-09-02T09:09:00+00:00", "estimated_runway":"2020-09-02T09:09:00+00:00","actual_runway":"2020-09-02T09:09:00+00:00"},"航空公司":{"name": "印度航空","iata":"AI","icao":"AIC"},"flight":{"number":"560","iata":"AI560","icao":"AIC560" ,"代码共享":null},"飞机":{"注册":"VT-EXM","ia ta":"A20N","icao":"A20N","icao24":"800C4B"},"live":null},{"flight_date":"2020-09-01","flight_status":"登陆","departure":{"airport":"Tirupati","timezone":"Asia/Kolkata","iata":"TIR","icao":"VOTP","terminal":null,"gate" :null,"delay":null,"scheduled":"2020-09-01T10:20:00+00:00","估计":"2020-09-01T10:20:00+00:00","实际":"2020-09-01T10:06:00+00:00","estimated_runway":"2020-09-01T10:06:00+00:00","actual_runway":"2020-09-01T10: 06:00+00:00"},"arrival":{"airport":"Hyderabad Airport","timezone":"Asia/Kolkata","iata":"HYD","icao":"VOHS", "终端":"3","登机口":null,"行李":null,"延迟":null,"预定":"2020-09-01T11:40:00+00:00","估计": "2020-09-01T11:40:00+00:00","实际":"2020-09-01T10:51:00+00:00","estimated_runway":"2020-09-01T10:51:00 +00:00","actual_runway":"2020-09-01T10:51:00+00:00"},"airline":{"name":"印度航空","iata":"AI"," icao":"AIC"},"flight":{"number":"560","iata":"AI560","icao":"AIC560","codeshared":null},"aircraft":null, "live":null},{"flight_date":"2020-09-01","flight _status":"landed","departure":{"airport":"Indira Gandhi International","timezone":"Asia/Kolkata","iata":"DEL","icao":"VIDP","terminal ":"3","gate":"29B","delay":6,"scheduled":"2020-09-01T06:50:00+00:00","estimated":"2020-09-01T06 :50:00+00:00","实际":"2020-09-01T06:56:00+00:00","estimated_runway":"2020-09-01T06:56:00+00:00", "actual_runway":"2020-09-01T06:56:00+00:00"},"arrival":{"airport":"Hyderabad Airport","timezone":"Asia/Kolkata","iata":" HYD","icao":"VOHS","terminal":"2","gate":null,"baggage":null,"delay":null,"scheduled":"2020-09-01T09:20: 00+00:00","估计":"2020-09-01T09:20:00+00:00","实际":null,"estimated_runway":null,"actual_runway":null},"航空公司": {"name":"印度航空","iata":"AI","icao":"AIC"},"flight":{"number":"560","iata":"AI560","icao ":"AIC560","codeshared":null},"aircraft":{"registration":"VT-EXM","iata":"A20N","icao":"A20N","icao24":"800C4B "},"live":null},{"flight_date":"2020-09-01","flight_status":"landed","departure":{"airport":"Hyderabad Airport","timezone":"亚洲/加尔各答","iata":"HYD","icao":"VOHS","terminal":null,"gate":null,"delay":null,"scheduled":"2020-09-01T12:45: 00+00:00","估计":"2020-09-01T12:45:00+00:00","实际":"2020-09-01T12:41:00+00:00","estimated_runway" :"2020-09-01T12:41:00+00:00","actual_runway":"2020-09-01T12:41:00+00:00"},"到达":{"机场":"英迪拉·甘地International","timezone":"Asia/Kolkata","iata":"DEL","icao":"VIDP","terminal":"3","gate":null,"baggage":null,"延迟":null,"预定":"2020-09-01T14:55:00+00:00","估计":"2020-09-01T14:55:00+00:00","实际":" 2020-09-01T14:42:00+00:00","estimated_runway":"2020-09-01T14:42:00+00:00","actual_runway":"2020-09-01T14:42:00+ 00:00"},"airline":{"name":"印度航空","iata":"AI","icao":"AIC"},"flight":{"number":"560", "iata":"AI560","icao":"AIC560","codeshared":null},"aircraft":null,"live":null}]}

【问题讨论】:

  • 好吧,api_response 中没有“results”这样的键,您可以尝试使用浏览器访问您的url 以查看 API 返回的内容
  • 1.您需要撤销刚刚公开共享的私钥。 2. 当你打印响应时,你看到了什么?你认为一个结果键吗?
  • 能否请您显示代码行“ print(api_response)”的结果?
  • 结果太大,无法评论,我如何在这里分享结果?抱歉,我对 stackoverflow 还是很陌生。
  • 试试for flight in api_response['data']:

标签: python json api python-requests


【解决方案1】:

试试这个。它访问键 data 而不是键 results (响应中可能不存在),并且在访问飞行对象中的 live 键时不会引发 TypeError,这可能为 null (当它在地面上时)。

import requests

params = {
  'access_key': access_key,
  'airline_name': 'Air India',
  'flight_number': 560
}


results = requests.get('http://api.aviationstack.com/v1/flights', params=params)

api_response = results.json()

for flight in api_response['data']:
    if flight.get('live') and not flight['live']['is_ground']:
        print('{} flight {} from {} ({}) to {} ({}) is in the air.'.format(
            flight['airline']['name'],
            flight['flight']['iata'],
            flight['departure']['airport'],
            flight['departure']['iata'],
            flight['arrival']['airport'],
            flight['arrival']['iata']))
    else:
        print("All flights landed.")

【讨论】:

  • 感谢您的回复。这给了我format function is not called on str
  • 修复了一个小的打印错误@YajasMalhotra
  • 非常感谢。这行得通。需要明确的是,问题是如果航班降落,它会给出“live”的非类型?
  • 是的,您访问了flight['live'],但这是 null,所以它说 I can read null
猜你喜欢
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
  • 2023-01-11
  • 1970-01-01
相关资源
最近更新 更多