JSON响应返回None时如何处理

时间:2019-07-17 16:23:54

标签: python django

我有一个RESTful API调用cwObj.get_opportunities(),以JSON响应的形式返回一组记录。从响应中,我针对第二个API调用ID引用了每个记录中的cwObj.get_tickets_by_opportunity()。此调用将返回第二组记录。但是,通常在第二个API调用返回的JSON响应中没有特定ID的记录。 API期望每个单独的调用都有记录,因此,如果没有记录,则会抛出IndexError: list index out of range。此外,当我对第二个API调用中引用的ID进行硬编码时,我可以毫无错误地检索到我想要的数据。

注释cwObj是我的API调用的基础...

opportunities = cwObj.get_opportunities()

for opportunity in opportunities:
    try:
        temp = opportunity['id']
        opportunity_id = str(temp)
        presales_ticket = cwObj.get_tickets_by_opportunity(opportunity_id)
        presales_engineer = presales_ticket[0]['owner']['name']
    except KeyError:
        presales_engineer = None

3 个答案:

答案 0 :(得分:0)

我不知道我是否很好地理解了这个问题。您基本上想检查收到的结果中是否有特定的key。如果是这种情况,您可以尝试以下方法:

opportunities = cwObj.get_opportunities()

for opportunity in opportunities:
    if 'id' in opportunity:
        temp = opportunity['id']
        opportunity_id = str(temp)
        presales_ticket = cwObj.get_tickets_by_opportunity(opportunity_id)
        presales_engineer = presales_ticket[0]['owner']['name']
    else:
        # What to do if there is no 'id' as key of opportunity

答案 1 :(得分:0)

我不确定您到底在寻找什么。但是如果您不需要检查,请输入 只需使用

if opportunity['id'] is not None:
   temp = opportunity['id']

答案 2 :(得分:0)

您确定cwObj.get_tickets_by_opportunity()没有返回空列表吗?

opportunities = cwObj.get_opportunities()

for opportunity in opportunities:
    try:
        temp = opportunity['id']
        opportunity_id = str(temp)
        presales_ticket = cwObj.get_tickets_by_opportunity(opportunity_id)
        if presales_ticket:
            if 'owner' in presales_ticket[0]:
                presales_engineer = presales_ticket[0]['owner']['name']
        else:
            # default presales ticket dict
    except KeyError:
        presales_engineer = None