JSON 中的 KeyError 访问字段

KeyError accessing field in JSON

有人可以帮助我访问以下 API 响应中的 "pagination" 字段吗?我尝试了下面的代码,但出现错误 'pagination'。它适用于 'title',所以我不确定有什么不同。完整错误如下。

Traceback (most recent call last):
  File "myscript.py", line 172, in <module>
    pag_object = (data['pagination'])
KeyError: 'pagination'

我的代码:

response = requests.get("https://api.weather.gov/alerts?limit=1", timeout=5)
data = response.json()
pag_object = (data['pagination'])

我已验证 JSON 有效。下面的片段。

{
    "@context": [
        "https://raw.githubusercontent.com/geojson/geojson-ld/master/contexts/geojson-base.jsonld",
        {
            "wx": "https://api.weather.gov/ontology#",
            "@vocab": "https://api.weather.gov/ontology#"
        }
    ],
    "type": "FeatureCollection",
    "features": [{
        "id": "http://api.weather.gov/alerts/NWS-IDP-PROD-KEEPALIVE-22613",
        "type": "Feature",
        "properties": {
            "@type": "wx:Alert",
            "id": "NWS-IDP-PROD-KEEPALIVE-22613",
            "areaDesc": "Montgomery",
            "geocode": {
                "UGC": [
                    "MDC031"
                ],
                "SAME": [
                    "024031"
                ]
            },
            "affectedZones": [
                "http://api.weather.gov/zones/county/MDC031"
            ],
            "references": [],
            "sent": "2018-05-21T14:05:51+00:00",
            "event": "Test Message",
            "senderName": "NWS",
            "description": "Monitoring message only. Please disregard.",
            "parameters": {
                "PIL": [
                    "NWSKEPWBC"
                ],
                "BLOCKCHANNEL": [
                    "CMAS",
                    "NWEM"
                ]
            }
        }
    }],
    "title": "Watches, warnings, and advisories",
    "pagination": {
        "next": "http://api.weather.gov/alerts?limit=1&cursor=eyJ0IjoxNTI2OTExNTUxLCJpIjoiTldTLUlEUC1QUk9ELUtFRVBBTElWRS0yMjYxMyJ9"
    }
}

该服务并不总是包含分页键。如果没有更多的数据页,则省略该键。

对其进行测试(if 'pagination' in data:),指定默认值(data.get('pagination', {}))或使用 try...except KeyError 异常处理程序来处理 link 缺失。