【问题标题】:How do you parsing nested JSON data for specific information?您如何解析嵌套的 JSON 数据以获取特定信息?
【发布时间】:2021-02-11 07:21:27
【问题描述】:

我正在使用国家气象服务 API,当您使用特定 URL 时,您会返回 JSON 数据。到目前为止,我的程序可以抓取所有内容,包括 155 小时的天气数据。

  • 简单地说,我正在尝试解析数据并获取天气 最近一小时,但所有内容都在嵌套数据结构中。

我的代码、JSON 数据和更多信息如下。任何帮助表示赞赏。

import requests
import json

def get_current_weather():  #This method returns json data from the api
    url = 'https://api.weather.gov/gridpoints/*office*/*any number,*any number*/forecast/hourly'
    response = requests.get(url)
    full_data = response.json()
    return full_data  

def main():   #Prints the information grabbed from the API
    print(get_current_weather())

if __name__ == "__main__":
    main()

在 JSON 响应中,在您获得我想要获得的“shortForecast”数据之前,我得到了 3 层。第一个嵌套是'properties,之前的一切都与我的程序无关。第二个嵌套是“周期”,每个周期都是一个新的小时,0 是最新的。最后,我只需要在第一个或多个周期[0] 中获取“shortForcast”。

{
    "@context": [
        "https://geojson.org/geojson-ld/geojson-context.jsonld",
        {
            "@version": "1.1",
            "wx": "https://api.weather.gov/ontology#",
            "geo": "http://www.opengis.net/ont/geosparql#",
            "unit": "http://codes.wmo.int/common/unit/",
            "@vocab": "https://api.weather.gov/ontology#"
        }
    ],
    "type": "Feature",
    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
                *data I'm not gonna add*
            ]
        ]
    },
    "properties": {
        "updated": "2021-02-11T05:57:24+00:00",
        "units": "us",
        "forecastGenerator": "HourlyForecastGenerator",
        "generatedAt": "2021-02-11T07:12:58+00:00",
        "updateTime": "2021-02-11T05:57:24+00:00",
        "validTimes": "2021-02-10T23:00:00+00:00/P7DT14H",
        "elevation": {
            "value": ,
            "unitCode": "unit:m"
        },
        "periods": [
            {
                "number": 1,
                "name": "",
                "startTime": "2021-02-11T02:00:00-05:00",
                "endTime": "2021-02-11T03:00:00-05:00",
                "isDaytime": false,
                "temperature": 18,
                "temperatureUnit": "F",
                "temperatureTrend": null,
                "windSpeed": "10 mph",
                "windDirection": "N",
                "icon": "https://api.weather.gov/icons/land/night/snow,40?size=small",
                "shortForecast": "Chance Light Snow",
                "detailedForecast": ""
            },
            {
                "number": 2,
                "name": "",
                "startTime": "2021-02-11T03:00:00-05:00",
                "endTime": "2021-02-11T04:00:00-05:00",
                "isDaytime": false,
                "temperature": 17,
                "temperatureUnit": "F",
                "temperatureTrend": null,
                "windSpeed": "12 mph",
                "windDirection": "N",
                "icon": "https://api.weather.gov/icons/land/night/snow,40?size=small",
                "shortForecast": "Chance Light Snow",
                "detailedForecast": ""
            },

好的,所以我不想再次编辑所有内容,所以这是新的 get_current_weather 方法。我能够进入'时期,但在那之后我仍然很难过。这是新方法。

def get_current_weather():  
    url = 'https://api.weather.gov/gridpoints/ILN/82,83/forecast/hourly'
    response = requests.get(url)
    full_data = response.json()
    return full_data['properties'].get('periods')

【问题讨论】:

  • 通过使用密钥。示例fulldata['properties']['updated']
  • full_data['properties']['periods'][0]['shortForecast] 将在第一个元素中为您提供 shortForecast 键的值。

标签: python json parsing


【解决方案1】:

对于字典对象,可以多次使用索引访问嵌套元素。

因此,对于您的字典对象,您可以使用以下命令获取主字典中键 periods 下的字典列表中第一个元素的键 shortForecast 的值:

full_data['properties']['periods'][0]['shortForecast']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多