【发布时间】:2014-03-26 21:43:33
【问题描述】:
我正在尝试使用 Python 从包含有关歌曲的元数据的 JSON 对象中提取几个元素。为了测试信息是否可用,我对每个元数据元素都使用了 try 语句。此外,对于稍后需要在程序中进行的一些字符串处理,我将每个值保存在不同的变量中。
关于如何改进以下代码以便不为每个不同的元数据值创建 try/except 语句的任何建议?
if len(r['response']['songs']) is not 0:
# Request information about the artist
artist_desc_string = "http://developer.echonest.com/api/v4/artist/terms?api_key="+api_key+\
"&name="+artist+"&format=json"
r2 = requests.get(artist_desc_string).json()
# Extract information from the song JSON
try:
title = r['response']['songs'][0]['title']
except (IndexError, KeyError):
title = "NULL"
try:
artist_name = r['response']['songs'][0]['artist_name']
except (IndexError, KeyError):
artist_name = "NULL"
try:
artist_location = r['response']['songs'][0]['artist_location']['location'].replace(',','*')
except (IndexError, KeyError):
artist_location = "NULL"
try:
...
...
【问题讨论】:
-
这个问题似乎是题外话,因为它属于codereview.stackexchange.com
-
如果您只是想处理最后一个元素上的 KeyError,您可以查看
dict.get,但由于您在查找路径的整个长度上捕获任何东西,并不是真的。您可以将路径放在列表中并循环遍历它们,但这只能说更简洁,而且可能更慢。 -
只是一个观察:您始终可以将
r['response']['songs'][0]分配给单个变量,看看它是如何重复使用的。
标签: python json error-handling