JSON数据中的访问字段 [英] Access Field in JSON Data

查看:170
本文介绍了JSON数据中的访问字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON格式的API响应.如果要提取诸如地理编码之类的字段,我该怎么做?将响应放入JSON是否多余?我收到一个错误,说列表索引必须是整数,而不是str.预先感谢,对此不陌生.

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.

我尝试过:

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

推荐答案

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

Error is in the hierarchy that you use here:

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

正确的是:

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

这篇关于JSON数据中的访问字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆