Access Field in JSON Data

南笙酒味 提交于 2019-12-11 14:53:06

问题


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


来源:https://stackoverflow.com/questions/50028427/access-field-in-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!