Home>

The following response is returned after hitting an API.
I just want to get thestatusvalue returned (I want to get the Critical below). Can you tell me how to get it?

res = curl XXXXXX

The result ofprint (res)below.
If this is value = res ['alert']
"byte indices must be integers or slices, not str"
Will give an error.

{"alerts":
    [
       {"id": "3XXXXXXX", "status": "CRITICAL", "monitorId": "3XXXXX", "type": "connectivity", "openedAt": 1535526664, "hostId": "3XXXX"
        }
    ]
}
  • Answer # 1

    How about this?
    Also pay attention to the spelling of alerts.

    value = res ['alerts'] [0] ['status']

    In this environment
    value = res ['alerts']
    "byte indices must be integers or slices, not str"
    KeyError:'alerts'has occurred but I don't know why.

  • Answer # 2

    value = dct ['alerts'] [0] ['status']
    How about that?
    Is ['alert'] in the question sentence a mistake of ['alerts']?
    Here are the ipython results:

    In [1]: dct = {"alerts":
       ...: [
       ...: {"id": "3XXXXXXX", "status": "CRITICAL", "monitorId": "3XXXXX", "type": "connectivity", "ope
       ...: nedAt ": 1535526664," hostId ":" 3XXXX "
       ...:
       ...:]
       ...:
       ...:
    In [2]: dct
    Out [2]:
    {'alerts': [{'hostId': '3XXXX',
       'id': '3XXXXXXX',
       'monitorId': '3XXXXX',
       'openedAt': 1535526664,
       'status': 'CRITICAL',
       'type': 'connectivity'}]}
    In [3]: dct ['alerts']
    Out [3]:
    [{'hostId': '3XXXX',
      'id': '3XXXXXXX',
      'monitorId': '3XXXXX',
      'openedAt': 1535526664,
      'status': 'CRITICAL',
      'type': 'connectivity'}]
    In [4]: ​​dct ['alerts'] ['ststus']
    -------------------------------------------------- -------------------------
    TypeError Traceback (most recent call last)
    <ipython-input-4-fbe317a82bfe>in<module>()
    ---->1 dct ['alerts'] ['ststus']
    TypeError: list indices must be integers or slices, not str
    In [5]: dct ['alerts'] [0]
    Out [5]:
    {'hostId': '3XXXX',
     'id': '3XXXXXXX',
     'monitorId': '3XXXXX',
     'openedAt': 1535526664,
     'status': 'CRITICAL',
     'type': 'connectivity'}
    In [6]: dct ['alerts'] [0] ['status']
    Out [6]: 'CRITICAL'
    In [7]: