访问JSON数据中的字段

时间:2018-04-25 17:46:30

标签: python json python-2.6

我有以下JSON格式的API响应。如果我想提取一个字段,比如地理编码,我该怎么办呢?将响应放在JSON中是多余的吗?我得到一个错误,说列表索引必须是整数,而不是str。在此先感谢,对此不熟悉。

我试过了:

import requests
import json

response = requests.get("https://api.weather.gov/alerts/active")

data = response.json()
json.loads(data['features']['id'][0]['properties'][0]['geocode'][0])

以下是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": "https://api.weather.gov/alerts/NWS-IDP-PROD-2791383-2596094",
            "properties": {
                "@id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2791383-2596094",
                "id": "NWS-IDP-PROD-2791383-2596094",
                "geocode": {
                    "UGC": [
                        "PZZ560"
                    ],
                    "SAME": [
                        "057560"
                    ]
                },
                "references": [
                    "https://api.weather.gov/alerts/NWS-IDP-PROD-2790941-2595876"
                ],
                "status": "Actual",
                "parameters": {
                    "NWSheadline": [
                        "SMALL CRAFT ADVISORY IN EFFECT"
                    ],
                    "eventEndingTime": [
                        "2018-04-26T21:00:00-07:00"
                    ]
                }
            }
        },
    ],
    "title": "Current watches, warnings, and advisories"
}

1 个答案:

答案 0 :(得分:1)

错误位于您在此处使用的层次结构中:

json.loads(data['features']['id'][0]['properties'][0]['geocode'][0])

正确的是:

json.loads(data['features'][0]['properties']['geocode'])