如何访问JSON响应的元素

时间:2019-01-30 08:04:22

标签: python python-3.x

从那时起,我有两种类型的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时,则该代码根本无法运行。

1 个答案:

答案 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
)