简体   繁体   中英

KeyError accessing field in JSON

Can someone help me access the "pagination" field in the following API response? I have tried the code below but get an error 'pagination'. It works for 'title' so I'm not sure what's different. Full error below.

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

My code:

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

I have verified that the JSON is valid. Snippet below.

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

The service doesn't always include a pagination key. If there are no further pages of data, the key is omitted.

Test for it ( if 'pagination' in data:) , specify a default value ( data.get('pagination', {}) ) or use a try...except KeyError exception handler to deal with the link missing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM