Search code examples
pythonpython-3.10structural-pattern-matching

Match/Case used to decide what keys JSON response contains


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]:]

Solution

  • 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.