Как вернуть Id определенного объекта с определенным статусом?

Вот пример респонса:

[
  {
    "type": 2,
    "id": "32d885cd-1e61-427a-b5d7-3025fe078ff2",
    "campaignId": 24,
    "status": 1,
    "endDate": "2021-08-30T17:21:19.031844",
    "name": "SecondName"
  },
  {
    "type": 1,
    "id": "bdde6b45-fba1-4290-ac6a-ff3158967439",
    "campaignId": 25,
    "status": 1,
    "endDate": "2021-08-31T00:21:19.123064",
    "name": "TestName"
  },
  {
    "type": 2,
    "id": "1d687c58-ed71-4c34-a7f9-8924a4a307f2",
    "campaignId": 25,
    "status": 2,
    "endDate": "2021-08-31T00:21:21.123064",
    "name": "3-rdName"
  }
]

Вот пример моего кода, я его обернул в Try->Except, так как допустимо пустой респонс.

   req = requests.get(url, headers=headers)
   assert_that(req.status_code).is_equal_to(200)
   res = req.json()
   try:
      res[0]['id']
      return res[0]['id']
   except IndexError:
       print("There are the empty response")

Данный код возвращает первый "id": "32d885cd-1e61-427a-b5d7-3025fe078ff2". Как задать правильно условие, чтоб возвращалось Id объекта с определенным status? Должно выглядеть примерно следующим образом, но не уверен:

active_bonus = req.json()
pending_bonus = req.json()
try:
   if active_bonus['status'] == 1:
       return active_bonus['id']
   elif pending_bonus['status'] == 2:
       return pending_bonus['id']
except IndexError:
    print("There are the empty response")

Данный код естественно не работает!


Ответы (2 шт):

Автор решения: passant

Четыре раза прочел -так и не понял, что вам надо сделать. Но вот так:

for active_bonus in res:
    if active_bonus['status']==1:
        print (active_bonus['id'])

вы получаете "Id объекта с определенным status"

→ Ссылка
Автор решения: Daniel

Я не очень понял, что вы хотите, но могу предложить такой вариант:

active_bonus = req.json()
pending_bonus = req.json()
try:
   for i in range(len(active_bonus)):
       if active_bonus[i]['status'] == 1:
           return active_bonus[i]['id']
       if pending_bonus[i]['status'] == 2:
            return pending_bonus[i]['id']
except IndexError:
    print("There are the empty response")
→ Ссылка