Access Field in JSON Data

2019-08-16 01:14发布

问题:

I have an API response in the following JSON format. If I want to extract a field, such as geocode, how would I do so? Is it redundant to put the response in JSON? I get an error saying the list indices must be integers, not str. Thanks in advance, new to this.

I've tried:

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])

Below is JSON data:

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

Error is in the hierarchy that you use here:

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

Correct one would be:

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