Match/Case used to decide what keys JSON response contains

565 Views Asked by At

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}]}
  1. I need to decide if it's 'data' or 'errors'
  2. After that if it's 'data', I need to decide if there is a key on position [0] of the list
    'id' -> [eg. if 'id' in r['data'][0]:]
    or
    'media' -> [eg. if 'media' in r['data'][0]:]
2

There are 2 best solutions below

0
Ajax1234 On BEST ANSWER

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.

2
Tim Roberts On

The best way is the simplest.

if 'errors' in response:
    print( "Error", response['errors'][0]['code'] )
elif 'id' in response['data'][0]:
    print( "ID is", response['data'][0]['id'] )
elif 'media' in response['data'][0]:
    print( "Media is", response['data'][0]['media'] )
else:
    print( "Not recognized." )