【发布时间】: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键的值。