I am trying to apply a match/case in my script where I want to do some action based on the JSON response from the API call:
response_types =
1. -> {'data': [{'id': 1485037059173588994}]}
2. -> {'data': [{'media': 1423364523411623943}]}
3. -> {'errors': [{'code': 404}]}
'data'
or 'errors'
'data'
, I need to decide if there is a key on position [0]
of the list 'id'
-> [eg. if 'id' in r['data'][0]:
]'media'
-> [eg. if 'media' in r['data'][0]:
]Using match-case
is pretty straightforward here:
match response:
case {'data': [{'id': _id}]} if _id > 51515: #using a guard, per your comment
print('response 1', _id)
case {'data': [{'media': media}, *_]}:
print('response 2', media)
case {'errors': [{'code': code}, *_]}:
print('response 3', code)
Note: using a throwaway wildcard *_
is necessary to ensure that the case
matches data
key lists of lengths >=1
.