Drew Bennett
Drew Bennett

Reputation: 483

Weather Underground Parsing Python

I am trying to separate the code for weather undergrounds api by day. Currently, I can get the array for forecastday, but can't get each array for fcttext and title. Here is my code thus far in python and the data I want to pull:

import requests
from pprint import pprint
import json

r = requests.get("http://api.wunderground.com/api/id/forecast10day/q/CA/San_Francisco.json")
data = r.json()
pprint (data['forecast']['txt_forecast']['forecastday'])


"forecastday": [
    {
    "period":0,
    "icon":"partlycloudy",
    "icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif",
    "title":"Thursday",
    "fcttext":"Cloudy early with peeks of sunshine expected late. High 54F. Winds W at 10 to 20 mph.",
    "fcttext_metric":"Cloudy skies early, then partly cloudy this afternoon. High 12C. Winds W at 15 to 30 km/h.",
    "pop":"0"
    }
    ,
    {
    "period":1,
    "icon":"nt_mostlycloudy",
    "icon_url":"http://icons.wxug.com/i/c/k/nt_mostlycloudy.gif",
    "title":"Thursday Night",
    "fcttext":"Partly cloudy this evening, then becoming cloudy after midnight. Low 38F. Winds N at 5 to 10 mph.",
    "fcttext_metric":"Partly cloudy early followed by cloudy skies overnight. Low 3C. Winds N at 10 to 15 km/h.",
    "pop":"0"
    }
    ,
    {
    "period":2,
    "icon":"chancerain",
    "icon_url":"http://icons.wxug.com/i/c/k/chancerain.gif",
    "title":"Friday",
    "fcttext":"Light rain early...then remaining cloudy with showers in the afternoon. High 52F. Winds NE at 10 to 15 mph. Chance of rain 60%.",
    "fcttext_metric":"Light rain early...then remaining cloudy with showers in the afternoon. High 11C. Winds NE at 15 to 25 km/h. Chance of rain 60%.",
    "pop":"60"
    }

Upvotes: 0

Views: 538

Answers (1)

alxwrd
alxwrd

Reputation: 2470

The value in data['forecast']['txt_forecast']['forecastday'] is a list of dictionaries. So you will need to loop over that list to get the items out of it.

for forecastday in data['forecast']['txt_forecast']['forecastday']:
    print(forecastday['title'])
    print(forecastday['fcttext'])

Produces:

Thursday
Cloudy early with peeks of sunshine expected late. High 54F. Winds W at 10 to 20 mph.
etc...

Upvotes: 1

Related Questions