The link below returns Json data. I an getting data from several elements and there are times when the data point is just not available and the mapping does not exists. If item does not exists I want my variable set to blank so it can continue instead of erroring out and stopping.
import requests
import pandas as pd
import json
gameId = 220808023
url = 'http://site.api.espn.com/apis/site/v2/sports/football/nfl/summary'
payload = {'event':gameId}
jsonData = requests.get(url,headers = {'User-agent': 'Chrome/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0'}, params=payload).json()
Venue = [jsonData['gameInfo']['venue']['id']]
Full link
http://site.api.espn.com/apis/site/v2/sports/football/nfl/summary?event=220808023
CodePudding user response:
import requests
import pandas as pd
import json
gameId = 220808023
url = 'http://site.api.espn.com/apis/site/v2/sports/football/nfl/summary'
payload = {'event':gameId}
jsonData = requests.get(url,headers = {'User-agent': 'Chrome/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0'}, params=payload).json()
venue = jsonData.get("gameInfo",{}).get("venue",{}).get("id","")
# .get(att,default) accepts a second parameter which is the returned value if cannot find the dict attribute. If you set it with blank text, venue will value empty string
CodePudding user response:
Your data does not contains what you are looking for.
import json
import requests
gameId = 220808023
url = 'http://site.api.espn.com/apis/site/v2/sports/football/nfl/summary'
payload = {'event': gameId}
jsonData = requests.get(
url,
headers={'User-agent': 'Chrome/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0'},
params=payload
).json()
# This simple print would have saved you from investigation:
print(json.dumps(jsonData, indent=4))
# > jsonData['gameInfo'] = {
# > "attendance": 0
# > }
# This is a better way to try if a key exist in your response
try:
gameInfo = jsonData['gameInfo']
try:
venue = gameInfo['venue']
try:
id = venue['id']
Venue = id
except KeyError:
print('venue data doesnt contains "id"')
except KeyError:
print('gameInfo data doesnt contains "venue"')
except KeyError:
print('json data doesnt contains "gameInfo"')
Keep in mind using PEP8 style is a good practice, and PEP8 recommand Snake case https://en.wikipedia.org/wiki/Snake_case
CodePudding user response:
You can check if the dictionary has a specific key by key in dic.
So, in principle, you can avoid KeyError by checking the existence of the key before querying the value for the key to the dictionary.
In order to avoid ugly nested if statements, you can define a wrapper class that checks the key existence when queried. The point is in python, accessing values by dic[key] is translated to calling the dic.__getitem__(key).
Example:
import requests
import pandas as pd
import json
gameId = 220808023
url = 'http://site.api.espn.com/apis/site/v2/sports/football/nfl/summary'
payload = {'event': gameId}
jsonData = requests.get(url, headers={
'User-agent': 'Chrome/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0'}, params=payload).json()
class MaybeDict:
def __init__(self, val):
self.val = val
def __getitem__(self, key):
if not self.val:
return MaybeDict(None)
if not key in self.val:
return MaybeDict(None)
return MaybeDict(self.val[key])
response = MaybeDict(jsonData)
print(response["gameInfo"]["venue"]["id"].val)
