Skip to main content
 首页 » 编程设计

python之访问 JSON 中的字段时出现 KeyError

2024年09月07日7虾米哥

有人可以帮我访问以下 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" 
    } 
} 

请您参考如下方法:

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

对其进行测试(if 'pagination' in data:),指定默认值(data.get('pagination', {}))或使用try...except KeyError 处理链接丢失的异常处理器。