我试图从地下气象API中提取历史数据。我修改了他们的Python示例代码(见下文)。当我运行这个命令时,我得到一个异常“TypeError:list index必须是整数,而不是str”JSON流包含一堆包含每日摘要信息(daily summary)的字段,但是我无法获取这些字段以及它们在此列表中的任何值。
我将URL放到JSON查看器中查看结构,但无法找出我做错了什么。任何帮助都将不胜感激。
import urllib2
import json
f = urllib2.urlopen('http://api.wunderground.com/api/d08c4738fb303c66/geolookup/conditions/q/CA/San_Francisco.json')
json_string = f.read()
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print "Current temperature in %s is: %s" % (location, temp_f)
f.close()
h = urllib2.urlopen('http://api.wunderground.com/api/d08c4738fb303c66/history_19760508/q/CA/San_Francisco.json')
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']['0']
print snow
h.close()
最佳答案
它在错误中指出了您的问题:不能用字符串索引列表:
>>> [1]['0']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> [1][0]
1
>>>
但你在这里做:
snow = parsed_json['history']['dailysummary']['0']
要解决问题,请将索引设置为整数:
snow = parsed_json['history']['dailysummary'][0]