【问题标题】:How to find out if a string part is included in a JSON response?如何确定字符串部分是否包含在 JSON 响应中?
【发布时间】:2022-01-16 16:13:10
【问题描述】:

假设 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,我应该如何处理?

【问题讨论】:

    标签: python json


    【解决方案1】:

    您不是在查看 JSON 字符串,而是在查看已解析的 Python 字典列表。所以你的问题是如何查找列表中的任何 dict 是否有键 incidentType 和值 card

    if any(i['incidentType'] == 'card' for i in response['incidents']):
        ...
    

    如果不能保证列表中的所有字典都有一个键 incidentType,请改用 i.get('incidentType')...

    【讨论】:

    • 感谢@deceze 的支持,它完美地解决了问题,我正在等待 Stack 要求的 7 分钟,以便将您的答案标记为解决方案,再次感谢!
    【解决方案2】:

    您的数据是一个 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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 2019-06-11
      • 2012-01-05
      • 2014-01-29
      • 1970-01-01
      相关资源
      最近更新 更多