import requests
r = requests.get("http://link-short.rf.gd/codes/hello/package.json")
r.json()
The codes are showing me
File "c:\file.py", line 3, in <module>
r.json()
File "C:\Users\88019\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 910, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\88019\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\88019\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\88019\AppData\Local\Programs\Python\Python39\lib\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)
What is the problem and how can I solve that ?
The problem is that JSON is not invalid. To be precise, the problem is not the link, but the file_2.txt file. So you have 2 solution: Check the file_2.text file and get a file that is correctly JSON, because this file is not. Or if you really can't get a JSON file, you can modify your code by inserting a request that applies to your file, because when you run your r (therefore a Requests) it makes assumptions about the encoding of the response based on the headers http. To change the encoding you can replace r.json () with r.text (), so like this:
import requests
r = requests.get ("http://link-short.rf.gd/codes/hello/file_2.txt")
r.text()
UPDATE
I noticed that you later changed the link in the question. Try these
import json
import requests
r = requests.get (http://link-short.rf.gd/codes/hello/package.json)
data = r.json()
or this, because it converts a string to access your JSON
import json
import requests
r = requests.get (http://link-short.rf.gd/codes/hello/package.json)
data = json.loads(r.text)
well http://link-short.rf.gd/codes/hello/file_2.txt does not supply a json.
So you could supply a link to a json file
You cannot call r.json() if r is not a json file. Since your URL points to some file_2.txt, it is not in json() format and hence r.json() will not help you.
Consider using r.text() instead
Related
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.
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 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
I am trying to write PyUnit test, where i am passing the URL to the test and the test needs to fetch the data and decode. The data is coming as raw payload. We are using REST. Here is the test code i have written :
#import urllib
import urllib.request
import json
proxy_support = urllib.request.ProxyHandler({"http":"http://local:8080"})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
request = urllib.request.Request("http://test.com/1")
response = urllib.request.urlopen(request)
encoding = response.info().get_param('charset', 'utf8')
data = json.loads(response.read().decode(encoding))
print (data)
The problem is that i am getting the following error :
data = json.loads(response.read().decode(encoding))
File "C:\Python34\lib\json__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "C:\Python34\lib\json\decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python34\lib\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)
Could someone help ? Thanks in advance.
Regards
Amit
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)