我从wunderground API和一行中提取此代码的数据:
sunsethour = parsed_json ['moon_phase']['sunset']['hour']
sunsetminute = parsed_json ['moon_phase']['sunset']['minute']
print "\nSunset is at: %s:%s" % (sunsethour, sunsetminute)
hightide = parsed_json ['tide']['tideSummary']['date']
print (hightide)
f.close()
当日落时间打印正常时,高位时间会产生错误“列表索引必须是整数,而不是str”
非常新的python,只是想找到自己的方式。请放轻松我,这里的一些对话似乎非常令人生畏。
截断示例:
{
"tide": {
"tideInfo": [
{
"tideSite": "Chelsea St. Bridge, Chelsea River, ...",
"lon": "-71.0233",
"units": "feet",
"tzname": "America/New_York",
"lat": "42.3867",
"type": "tide"
}
],
"tideSummaryStats": [
{
"minheight": 99.0,
"maxheight": -99.0
}
],
"tideSummary": []
}
}
答案 0 :(得分:3)
在没有看到源JSON的情况下,这是迄今为止我能给出的最好的:
hightide = parsed_json ['tide']['tideSummary']['date']
这假设根元素和两个子元素都是字典,可以通过字符串键访问。显然,这些数据元素之一是列表而不是字典:
parsed_json['tide'] # could be a list of tides?
parsed_json['tide']['tideSummary'] # could be a list of tide summaries?
parsed_json['tide']['tideSummary']['date'] # could be a list of dates?
所有这些都必须产生词典。查看值并查看它们中是否有任何实际列表:
aList = ['1','2','3']
aDict = {'1':1, '2':2, '3':3}
>>> aList['1']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> aDict['1']
1
<强>更新强>
从json结构的更新中,parsed_json ['tide']['tideSummary']
会导致问题。 tideSummary
的值是一个列表,虽然你的数据是空的,所以我不确定里面是什么。
如果它是包含日期值的摘要词典列表,那么您可以这样做:
# assume: parsed_json['tide']['tideSummary'] = [{"date":"value"}]
for summary in parsed_json['tide']['tideSummary']:
print summary['date']
...再次,这假设它们是{"date":"value"}