【发布时间】:2019-08-01 09:29:33
【问题描述】:
早上好;我正在尝试从 URL 生成的 JSON 文件中提取一些键值。
我能够毫无问题地从 URL 中提取 JSON(打印第 8 行以供参考)
def get_url():
api_conditions_url = 'http://magicseaweed.com/api/' + API_KEY + '/forecast/?spot_id=' + PUTSBOROUGH_SPOT_ID
print('Collecting data from - ' + api_conditions_url)
try:
f = urlopen(api_conditions_url)
except:
return []
json_currently = f.read()
print(json_currently)
f.close()
return json.loads(json_currently)
def main():
curr_conditions = get_url()
if ("absMinBreakingHeight" not in curr_conditions["swell"]):
print ("Error #001 JSON call failed, check your query is correct!]\n")
exit()
else:
print('it worked')
if __name__ == "__main__":
main()
JSON 文件如下所示:
{
"timestamp":1564617600,
"localTimestamp":1564617600,
"issueTimestamp":1564617600,
"fadedRating":0,
"solidRating":0,
"swell":{
"absMinBreakingHeight":1.3,
"absMaxBreakingHeight":2.03,
"probability":100,
"unit":"ft",
"minBreakingHeight":1,
"maxBreakingHeight":2,
"components":{
"combined":{
"height":3,
"period":6,
"direction":75.97,
"compassDirection":"WSW"
},
"primary":{
"height":2.5,
"period":6,
"direction":65.06,
"compassDirection":"WSW"
},
"secondary":{
"height":1.1,
"period":6,
"direction":160.71,
"compassDirection":"NNW"
}
}
},
"wind":{
"speed":5,
"direction":127,
"compassDirection":"NW",
"chill":60,
"gusts":6,
"unit":"mph"
},
"condition":{
"pressure":1017,
"temperature":61,
"weather":"10",
"unitPressure":"mb",
"unit":"f"
},
"charts":{
"swell":"https:\/\/charts-s3.msw.ms\/archive\/wave\/750\/1-1564617600-1.gif",
"period":"https:\/\/charts-s3.msw.ms\/archive\/wave\/750\/1-1564617600-2.gif",
"wind":"https:\/\/charts-s3.msw.ms\/archive\/gfs\/750\/1-1564617600-4.gif",
"pressure":"https:\/\/charts-s3.msw.ms\/archive\/gfs\/750\/1-1564617600-3.gif",
"sst":"https:\/\/charts-s3.msw.ms\/archive\/sst\/750\/1-1564617600-10.gif"
}
},
我在尝试解析 JSON 文件时收到以下错误 -
if ("absMinBreakingHeight" not in curr_conditions["swell"]):
TypeError: 列表索引必须是整数或切片,而不是 str"
【问题讨论】:
-
看起来 curr_conditions 是一个列表,而您只向我们展示了其中的一部分。
-
你的
try和except块中的f = urlopen(api_conditions_url)是否有可能失败并且get_url函数返回一个空列表? -
@AlexHall - 如何将其从列表更改为我可以调用的内容。我使用相同的代码毫无问题地提取了不同的 JSON 文件。我比较了两个 JSON 文件,看起来一样。
-
请分享完整的 JSON
-
我认为您的 json 可能是字典列表,即
[{}, {}],您可能需要对其进行迭代并检查。即curr_conditions[0]["swell"]