Let’s say the print of a JSON response print(response) is:
{'incidents': [{'text': 'FT', 'homeScore': 2, 'awayScore': 0, 'isLive': False, 'time': 90, 'addedTime': 999, 'incidentType': 'period'}, {'player': {'name': 'Jackson Porozo', 'firstName': '', 'lastName': '', 'slug': 'jackson-porozo', 'shortName': 'J. Porozo', 'position': 'D', 'userCount': 321, 'id': 978518}, 'playerName': 'Jackson Porozo', 'reason': 'Foul', 'id': 120118989, 'time': 90, 'addedTime': 4, 'isHome': False, 'incidentClass': 'yellow', 'incidentType': 'card'}
I’m wanting to find out if in this response we have included 'incidentType': 'card'.
For that I tried to use:
if "'incidentType': 'card'" in response:
print('Ok')
And I also tried using:
if "\'incidentType\': \'card\'" in response:
print('Ok')
both did not return Ok, how should I proceed?
>Solution :
You’re not looking at a JSON string, you’re looking at an already parsed Python list of dicts. So your question is how to find if any dict in the list has a key incidentType with value card:
if any(i['incidentType'] == 'card' for i in response['incidents']):
...
If it’s not guaranteed that all dicts in the list have a key incidentType, use i.get('incidentType') instead…