Cannot grab histoiral dailysummary values from API using JSON with Python

  • 1
  • Question
  • Updated 5 years ago
I am trying to pull historical weather values out of the History > Dailysummary JSON output and I am unable to get the key measures from there. I use the following Python code to grab the JSON content for SF on a random day in 1976. I can get the date out no problem, but when I try and grab Dailysummary variable values such as snow I get the following error report:

Traceback (most recent call last):
File "wu.py", line 22, in
snow = parsed_json['history']['dailysummary']['snow']
TypeError: list indices must be integers, not str

#### Code I use in Python

h = urllib2.urlopen('http://api.wunderground.com/api/d08c4...')
json_string = h.read()
parsed_json = json.loads(json_string)
date = parsed_json['history']['utcdate']['pretty']
print date

print type(parsed_json['history'])

snow = parsed_json['history']['dailysummary']['snow']
print snow
print type(snow)
Photo of jaybocconi

jaybocconi

  • 3 Posts
  • 1 Reply Like

Posted 5 years ago

  • 1
Photo of ajw

ajw

  • 6 Posts
  • 0 Reply Likes
It may not exist (at all) in the returned data. I just posted a similar issue. Did you try pasting that URL into your browser and looking at the returned text to see if it's sending you anything inside "dailysummary"?
Photo of Brendan Hayes

Brendan Hayes, Official Rep

  • 962 Posts
  • 123 Reply Likes
dailysummary is the last node on that page
Photo of jaybocconi

jaybocconi

  • 3 Posts
  • 1 Reply Like
I figured out the problem. The following change to the calls took care of it:

# Get the daily summary measures of weather
dailysumm = parsed_json['history']['dailysummary'][0]
print dailysumm
print "dailysumm is th following type"
print type(dailysumm)

print "Maxpressure is:"
maxpress = parsed_json['history']['dailysummary'][0]['maxpressurem']
print maxpress

print "Fog is:"
fog = parsed_json['history']['dailysummary'][0]['fog']
print fog
Photo of jaybocconi

jaybocconi

  • 3 Posts
  • 1 Reply Like
When I left out the [0] in the call for the measure I was getting an error saying I was dealing with a list rather than a dict structure. It works just fine now. Thanks