Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find out if a string part is included in a JSON response?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading