假設 JSON 回應的列印結果print(response)是:
{'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'}
我想知道我們是否在此回復中包含了'incidentType': 'card'.
為此,我嘗試使用:
if "'incidentType': 'card'" in response:
print('Ok')
我還嘗試使用:
if "\'incidentType\': \'card\'" in response:
print('Ok')
兩者都沒有回傳Ok,我應該如何進行?
uj5u.com熱心網友回復:
您不是在查看JSON 字串,而是在查看已決議的 Python 字典串列。因此,您的問題是如何查找串列中的任何 dict 是否具有incidentType帶有 value的鍵card:
if any(i['incidentType'] == 'card' for i in response['incidents']):
...
如果不能保證串列中的所有 dicts 都有一個 key incidentType,請i.get('incidentType')改用……
uj5u.com熱心網友回復:
您的資料是 python 字典。使用基本的 dict API 來實作你的邏輯
data = {'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'}]}
for entry in data['incidents']:
if entry.get('incidentType') == 'card':
print('Found')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/412315.html
標籤:
