JSON中的KeyError访问字段

时间:2018-05-21 14:31:56

标签: python json pagination python-2.6

有人可以帮助我访问以下API响应中的“分页”字段吗?我已经尝试了下面的代码,但得到错误'分页'。它适用于'标题'所以我不确定有什么不同。完全错误如下。

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"
    }
}

1 个答案:

答案 0 :(得分:2)

该服务并不总是包含分页键。如果没有其他数据页面,则省略该键。

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