从那时起,我有两种类型的JSON格式的答案,我想解析此信息。
response = {'success': True, 'alarms': [{'play_voice': True}, {'voice_url': 'my directory'}]}
response = {'success': True, 'alarms': [{'play_voice': False}]}
当我尝试此代码时,我将得到以下输出:
voice_prof = [alarm is not None for alarm in response['alarms'] if alarm.get('play_voice', 0) != 0][0]
当“ play_voice”为True时,我的代码可以正常工作,但我的“ play_voice”为False时,则该代码根本无法运行。
答案 0 :(得分:0)
我认为您想为play_voice
列表中包含该关键字的第一本词典的alarms
键的值,在这种情况下,列表理解的两面都是错误的,并且您需要以下内容:
voice_prof = [
alarm["play_voice"] # value for that key
for alarm in response["alarms"]
if "play_voice" in alarm # if it contains that key
][0]
一种更有效的实现方式是仅使用next
上的generator expression找到第一个这样的字典,而不是遍历整个alarms
列表:
voice_prof = next(
alarm["play_voice"] # value for that key
for alarm in response["alarms"]
if "play_voice" in alarm # if it contains that key
)