在Python中检查来自JSON响应的null对象

时间:2016-03-31 01:29:24

标签: python json dictionary

我有以下代码,它有效。我正在检查JSON对象是否具有完整字段并且不包含基础字段(Jira API,如果您感兴趣)。是否有更简洁的方法来编写for循环?

  public static void toString(ArrayList s)
  {
    System.out.println(s);
  }
}

1 个答案:

答案 0 :(得分:3)

您可以将dict.get与后备字典一起使用:

>>> issues = {'fields': {'assignee': None}}
>>> issues['fields']['assignee'] or {}  # fallback to an empty dictionary
{}
>>> (issues['fields']['assignee'] or {}).get('displayName', 'Unassigned')
'Unassigned'
for issue in myVals:
    assignee = (issue['fields']['assignee'] or {}).get('displayName', 'Unassigned')

或者定义后备字典,如下所示:

UNASSIGNED = {'displayName': 'Unassigned'}
for issue in myVals:
    assignee = (issue['fields']['assignee'] or UNASSIGNED)['displayName']