No JSON object could be decoded Python - python

I'm trying to get some data from this website. I can enter 'text' and 'longest_only' parameters but when I pass 'ontologies' param, it says No JSON object could be decoded. Here's the complete URL http://data.bioontology.org/annotator?text=lung cancer,bone marrow&ontologies=NCIT&longest_only=true
I'm using Python 2.7

The argument is ontologies[], since you can specify more than one. Your request should be similar to the one that the online search uses:
text=lung+cancer%2Cbone+marrow&ontologies%5B%5D=NCIT&longest_only=true&raw=true
Simply execute the same search there, and use the developer tools option of your favorite browser to check what is the actual payload being sent.

This is not an answer, but the only place I can show the error that I see when executing the sample code. I placed the code in a new module in main and run it in Python 3.4.
import requests
if __name__ == '__main__':
url = 'http://bioportal.bioontology.org/annotator'
params = {
'text': 'lung cancer,bone marrow',
'ontologies': 'NCIT',
'longest_only': 'true'
}
session = requests.Session()
session.get(url)
response = session.post(url, data=params)
data = response.json()
# get the annotations
for annotation in data['annotations']:
print (annotation['annotatedClass']['prefLabel'])
I receive the following error.
Traceback (most recent call last):
File "/Users/.../Sandbox/Ontology.py", line 21, in <module>
data = response.json()
File "/Users/erwin/anaconda/lib/python3.4/site-packages/requests/models.py", line 799, in json
return json.loads(self.text, **kwargs)
File "/Users/erwin/anaconda/lib/python3.4/json/__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "/Users/erwin/anaconda/lib/python3.4/json/decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/erwin/anaconda/lib/python3.4/json/decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)

Related

TD Ameritrade API 'Get Option Chain' giving <Response [200]> but I'm getting JSONDecodeError: Expecting value?

After generating the access_token (which works when I use it on TD Ameritrade's API website) I'm trying to get option chains for a stock. I can get it to work on TD Ameritrade's API website, and I get an 'OKAY' response when I run my code, but no JSON data attached, any idea why? My relevant code is below.
content = requests.get(url = https://api.tdameritrade.com/v1/marketdata/chains, params = params_dictionary, headers = access_token)
print(content)
print(repr(content.text))
data = content.json()
print(data)
but for my output I get
<Response [200]>
''
Traceback (most recent call last):
File "C:\Users\USER\Documents\GitHub\pythonfiles\TD Ameritrade API tests.py", line 98, in <module>
data = content.json()
File "C:\Users\USER\Anaconda3\lib\site-packages\requests\models.py", line 900, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\USER\Anaconda3\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\USER\Anaconda3\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\USER\Anaconda3\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
JSONDecodeError: Expecting value
It was a mistake on my part unshown in my question. I was accidentally using 'https://api.tdameritrade.com/v1/marketdata/https://api.tdameritrade.com/v1/marketdata/chains' for my URL. I'm unsure how this didn't break things, but this was my issue.

Python Rejects Valid JSON

I'm trying to process this JSON using python3:
http://www.bom.gov.au/fwo/IDV60701/IDV60701.94857.json
But I'm getting the following error:
Traceback (most recent call last):
File "./weath.py", line 41, in <module>
data1 = response.json()
File "/home/dz/anaconda3/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/home/dz/anaconda3/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/home/dz/anaconda3/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/home/dz/anaconda3/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
https://jsonlint.com/
Validates the JSON as valid, so I'm not sure why this is failing.
Here is the python code:
url = "http://www.bom.gov.au/fwo/IDV60701/IDV60701.94857.json"
response = requests.get(url)
data1 = response.json()
This was working 2 week ago.
How can I fix this?
This is an issue related to the specific service endpoint you're using. They have disabled web scraping through some mechanism.
If you look at your response object, you'll see it's a 403 (forbidden) with the following message:
Potential automated request detected! We are making changes to our website therefore web scraping is no longer supported. Please contact us by filling in the details at http://reg.bom.gov.au/screenscraper/screenscraper_enquiry_form/ and we will get in touch with you.
You can verify this for yourself:
response = requests.get("http://www.bom.gov.au/fwo/IDV60701/IDV60701.94857.json")
print(response.status_code) # 403
print(response.text) # above quote
When I ran this code:
import requests
url = "http://www.bom.gov.au/fwo/IDV60701/IDV60701.94857.json"
response = requests.get(url).text
print(response)
The print returned
Potential automated request detected! We are making changes to our website therefore web scraping is no longer supported. Please contact us by filling in the details at http://reg.bom.gov.au/screenscraper/screenscraper_enquiry_form/ and we will get in touch with you.
Seems like that website has disabled web-scraping or something

I got this error simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I hope you're doing good.
I'm trying to get the solar radiation values from this website 'solcast.com.au' .. I have went to their API documentation and followed it here ' https://docs.solcast.com.au/#forecasts-by-location' and I have applied the code:
import requests
url = 'https://api.solcast.com.au/world_radiation/forecasts?latitude= -33.865143&longitude=151.209900&api_key=MYAPI'
res = requests.get(url)
data = res.json()
forecast = data["forecasts"]["ghi"]
print('forecastss: {} dgree'.format(forecast))
So when I run the code I'm getting this error:
Traceback (most recent call last):
File "/home/pi/Desktop/solcastoo.py", line 5, in <module>
data = res.json()
File "/usr/lib/python3/dist-packages/requests/models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 518, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Would really appreciate your help.
As John mentioned, you need to specify in your request the format you're willing to receive.
You can do it by adding headers to your request:
import requests
url = 'https://api.solcast.com.au/world_radiation/forecasts?latitude= -33.865143&longitude=151.209900&api_key=API_KEY'
res = requests.get(url, headers={'Content-Type': 'application/json'})
data = res.json()
forecast = data["forecasts"][0]["ghi"]
print('forecastss: {} dgree'.format(forecast))
In their documentation they give you two additional options:
“Accepts” HTTP request header, eg “​application/json​” for ​JSON
“format” query string, eg “​format=json​” for ​JSON
Endpoint suffix file extension, eg “​forecasts.json​” for ​JSON
The second option doesn't work, at least for this specific request. The third option works, but it's a bit odd.
The first option is more commonly used in APIs, but be prepared to use other options too.
PS they say in the documentation that `headers={'Accepts': 'application/json'}
should give the desired result, so I'd assume it also could be a possibility in other endpoints.
Good luck

Can't get a valid response from a webpage containing json data

I've written a script in python to get response from a webpage. The data in that webpage are in json format. However, when I try like below I get an error. Can somebody give me any workaround as to how I can get a valid response?
Here is my failure attempt:
import requests
import json
URL = "https://www.sandicormls.com/agent/AgentSearch?officeSortOption=name&_=1516998894917&_keywordsAll=&officeLocation=&sortOption=rndsrt&_keywordsAgentName=&page=&typeIn=Realtor%2CBroker%2COwner%2COffice+Manager%2CAppraiser&searchMode=agent&officeName="
res = requests.get(URL,headers={'User-Agent':'Mozilla/5.0'})
print(res.json())
This is the traceback:
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python35-32\new_line_one.py", line 34, in <module>
print(res.json())
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\requests\models.py", line 892, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I just gave it a try and confirm that your code is fine as it works on my environment. Though, I run it on a Linux (Ubuntu 16.04) virtual machine.
You could check what data you are getting back
print(res.headers[‘content-type’])
or examine the content such as
print(res.text)

Attribute Error, Type Error, Name Error While trying to print simple JSON from server response?

I am trying to get JSON and print VIA python scirpt. I got response from server 200, not sure why i can not able print the file. Please help me on this!!
The Code used is:
Import Requests
response = requests.get("https://Site1/rest/settings/all-server-status", params={'serverId': '56cd7e4d2d0edcace915e674'}, verify=False)
json_data = json.loads(response.text)
I got below error:
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
json_data = json.loads(response.text)
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
I tried below statements also but no response:
json_data = json.loads(response)
json_data = json.loads(response.read())
The Json Sample output expecting is:
[{"id":"56cd7e4d2d0edcace915e674","protocol":"https","hostName":"x.x.x.x","port":443,"serverName":"Site1","status":"connected","connected":true}]
Thanks in advance!
The POST request you are making is not returning anything, however the Response 200 indicates the connection was successful(No SSL error etc).
The problem is here: params={'serverId': '56cd7e4d2d0edcace915e674'}.
I would suggest debugging your request.get().
Start by checking if the https://hostname.com/key=value is valid.

Categories