我正在尝试使用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:
...
...
答案 0 :(得分:3)
这样的事可能吗?
def get_or_dont(d,list_of_keys):
d2 = d
while list_of_keys:
try:
d2 = d2[list_of_keys.pop(0)]
if not list_of_keys: return d2
except:
break
return "Null"
r = {'response':{
'a':5,
'b':{'6':{'5':3}},
'c':[1,2,3]
}}
print get_or_dont(r['response'],["b","6"])
答案 1 :(得分:3)
也许这可能会有所帮助:
def get_value(d, keys):
try:
if keys:
for i in range(len(keys)):
key = keys[i]
return get_value(d[key], keys[i+1:])
return d
except (IndexError, KeyError):
return "Null"
>>> d = {'person': {'name': {'first': 'aamir'}}}
>>> get_value(d, ['person', 'name', 'first'])
aamir
答案 2 :(得分:1)
使用包含所有可能属性的for循环...
attribs = {'title': None, 'artist_name':None, 'location': None, 'etc': None}
for key in attribs:
try:
attribs[key] = r['response']['songs'][0][key]
except (IndexError, KeyError):
attribs[key] = "NULL"
这样你只需要管理dict attribs ...
就获取意外属性而言,您总是可以获取JSON对象的键并在attribs中创建更多条目