Eyal S.
Eyal S.

Reputation: 1161

Requests issue - No JSON object could be decoded

I'm new to python and I'm trying to convert some MATLAB code into python. I have a url from the NBA website in json format that I would like to parse and return as a dataframe. I have the following code so far:

import requests
url = 'http://stats.nba.com/stats/shotchartdetail?PlayerID=2544&TeamID=0&VsConference=&Location=&SeasonType=Regular+Season&RookieYear=&Season=2015-16&DateFrom=&ClutchTime=&GameID=&OpponentTeamID=0&DateTo=&GameSegment=&AheadBehind=&LastNGames=0&VsDivision=&LeagueID=&Position=&Outcome=&ContextMeasure=FGM&SeasonSegment=&Period=0&Month=0'
r = requests.get(url)
data = r.json()

I can see that the json loads on my browser by using the url and this also works in MATLAB but I get the following error message in python: No JSON object could be decoded

Any idea what the issue is?

Upvotes: 1

Views: 10450

Answers (2)

Eyal S.
Eyal S.

Reputation: 1161

I found the answer here:

Python Requests Client Error: Bad Request, but works after website has been opened in browser

Adding a user-agent works:

u_a = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36"
response = requests.get(url, headers={"USER-AGENT":u_a})

Upvotes: 1

Bernardo Meurer
Bernardo Meurer

Reputation: 2335

You can try getting the text element of r and converting to json, like this:

import requests
import json

url = 'http://stats.nba.com/stats/shotchartdetail?PlayerID=2544&TeamID=0&VsConference=&Location=&SeasonType=Regular+Season&RookieYear=&Season=2015-16&DateFrom=&ClutchTime=&GameID=&OpponentTeamID=0&DateTo=&GameSegment=&AheadBehind=&LastNGames=0&VsDivision=&LeagueID=&Position=&Outcome=&ContextMeasure=FGM&SeasonSegment=&Period=0&Month=0'
r = requests.get(url)
data = json.loads(r.text)

Although by copying and pasting your code it worked for me this might be a workaround.

Upvotes: 1

Related Questions