python - JSON Python MBTA API 请求

标签 python json

我一直在为 MBTA API 项目编写代码,但我需要一些帮助。我需要编写什么代码才能使 Python 识别出我正在搜索的 JSON 字段不存在?

这是我的代码:

import urllib, json, time

localtime = time.localtime(time.time())

if localtime.tm_hour <=4:
realHour = localtime.tm_hour - 4 + 24
else:
realHour = localtime.tm_hour - 4

realMin = localtime.tm_min

#url = "https://api-v3.mbta.com/predictions? 
filter[route]=134&filter[stop]=9147&filter[stop_sequence]=3,4,5,6,7,8,9,10, 
11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,
36,37,38,39,40,41,42,43,44,45,46,47,48,49,50&include=trip,vehicle"
url = "https://api-v3.mbta.com/predictions? 
filter[stop]=Mishawum0&include=trip"
response = urllib.urlopen(url)

data = json.loads(response.read())
test = data['data']               
# THIS IS WHERE I HAD THE PROBLEM
#                                  V
if data['data'][0]['attributes'] != None:
    firstDeparture = data['data'][0]['attributes']['departure_time']
    firstId = data['data'][0]['relationships']['trip']['data']['id']

    search = 1
    didIt = False
    if firstId == data['included'][0]['id']:
        headsign = data['included'][0]['attributes']['headsign']
        didIt = True
    if didIt == False and firstId == data['included'][search]['id']:
        headsign = data['included'][search]['attributes']['headsign']
        didIt = True
    search+=1
    if didIt == False and firstId == data['included'][search]['id']:
        headsign = data['included'][search]['attributes']['headsign']
        didIt = True
    search+=1
    if didIt == False and firstId == data['included'][search]['id']:
        headsign = data['included'][search]['attributes']['headsign']
        didIt = True
    search+=1
    if didIt == False and firstId == data['included'][search]['id']:
        headsign = data['included'][search]['attributes']['headsign']
        didIt = True
    search+=1
    if didIt == False and firstId == data['included'][search]['id']:
        headsign = data['included'][search]['attributes']['headsign']
        didIt = True
    search+=1
    if didIt == False and firstId == data['included'][search]['id']:
        headsign = data['included'][search]['attributes']['headsign']
        didIt = True
    t = "T"
    print(headsign)
    firDept = firstDeparture[11:19]

    minute = firDept[3:5]
    hour = firDept[0:2]
    print(minute)
    print(hour)
    hour1 = int(hour) - realHour
    min1 = int(minute) - realMin
    if min1 < 0:
        if hour1 > 0:
            min1 += (60*hour1)
    arrMin = min1

    if arrMin > 0:
        print("NEXT TRAIN TO " + headsign.upper() + " IN " + str(arrMin) +   " MINS THIS IS A FLAG STOP PLEASE BE IN FULL SIGHT OF ENGINEER AS TRAIN APPROACHES")
    elif arrMin == 0:
        print("STAND BACK " + headsign.upper() + " TRAIN")
else:
    print("NO ARRIVALS AT THIS TIME. FOR SCHEDULING INFORMATION, PLEASE VISIT WWW.MBTA.COM")

在显示 if data['data'][0]['attributes'] != None: 的区域周围是问题所在。它一直给我错误,而不是执行else。我究竟做错了什么?

Error:
Traceback (most recent call last):
  File "mbta_headsign.py", line 18, in <module>
    if data['data'][0]['attributes'] :
IndexError: list index out of range

最佳答案

该错误清楚地表明了您的问题。错误是:

Traceback (most recent call last): 
  File "mbta_headsign.py", line 18, in <module>
    if data['data'][0]['attributes'] != None: 
IndexError: list index out of range

IndexError 告诉您您正在尝试访问超出列表末尾的列表项。在本例中,您尝试访问 data['data'][0],并且此错误表明 data['data'] 实际上是一个空的列表。

而不是检查:

if data['data'][0]['attributes'] != None:

考虑检查:

if len(data['data']) > 0:

您可以按照我在评论中的建议并在 if 语句之前打印出 data['data'] 的值来验证这是否是问题所在。

关于python - JSON Python MBTA API 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52879707/

相关文章:

python - 操作 Pandas 数据框的数据

java - 如何解析使用 GSON 转义引号的 JSON

python - 在 Python 中将具有不同标题的 csv 文件与 Pandas 合并

python - 在ubuntu EC2深度学习实例中通过jupyter笔记本从s3读取数据

python - python中pickle.dump的使用

python - 检查文件夹大小是否大于特定大小的最快方法是什么?

python - 将 tensorflow 中具有不同等级的两个占位符相乘

javascript - 从 React 调用 API

json - AWS API 网关模型 : Invalid model schema specified

java - Gson 与 Hibernate - 尝试加载惰性属性时出错