Home > other >  If an object exists in JSON then print another value, if not, print nothing
If an object exists in JSON then print another value, if not, print nothing

Time:12-07

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}

url = f'https://api.sofascore.com/api/v1/sport/football/events/live'
response = requests.get(url, headers=headers).json()
events = response['events']
for event in events:
    List_of_Urls = []
    List_of_Urls.append(event['id'])

    slug = event['slug']

    for List_of_Url in List_of_Urls:
        try:
            url2 = f'https://api.sofascore.com/api/v1/event/{List_of_Url}/graph'
            response2 = requests.get(url2, headers=headers).json()
            
            if response2['graphPoints']:
                print(slug)
        except:
            pass

Response JSON example 1: https://api.sofascore.com/api/v1/event/9625897/graph

{
  "graphPoints": [
    {
      "minute": 1,
      "value": -2
    }

Response JSON example 2: https://api.sofascore.com/api/v1/event/9761921/graph

{
  "error": {
    "code": 404,
    "message": "Not Found"
  }
}

My idea is that if there is graphPoints in JSON, then printing the slug value, but in the direct if response2['graphPoints']: value for true or false doesn't work, how should I make it work?

CodePudding user response:

If its a JSON object I think you can just do:

if 'graphpoints' in response2:
    print(slug)

If its a dict, try:

if 'graphpoints' in response2.keys():
    print(slug)
  • Related