import sys
import requests
date = str(sys.argv[1])
from_currency=str(sys.argv[2]).upper()
to_currency= str(sys.argv[3]).upper()
amount=float(sys.argv[4])
response = requests.get(f"https://api.frankfurter.app/{date}?amount={amount}&from={from_currency}&to={to_currency}")
print(f"{amount} {from_currency} is {response.json()['rates'][to_currency]} {to_currency} on {date}")
I tried running the following command on the terminal
python main.py '2020-01-01' 'USD' 'GBP' 2
I was expecting "3 USD is 86.77 GBP on 2020-01-01", but instead I get this error, which I do not understand
Traceback (most recent call last):
File "C:\Users\samee\anaconda3\lib\site-packages\requests\models.py", line 910, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\samee\anaconda3\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\samee\anaconda3\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\samee\anaconda3\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)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\samee\OneDrive\Desktop\PAI\Assignments\Assignment 1b\main.py", line 34, in <module>
print(f"{amount} {from_currency} is {response.json()['rates'][to_currency]} {to_currency} on {date}")
File "C:\Users\samee\anaconda3\lib\site-packages\requests\models.py", line 917, in json
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: [Errno Expecting value] : 0
I ran your code, I am able to get the response. This error comes when sometime the website sends empty response.
By running your code, I got the response : 2.0 USD is 1.5147 GBP on 2020-01-01
To handle such empty or other response add Error Handling:
date = str(sys.argv[1])
from_currency=str(sys.argv[2]).upper()
to_currency= str(sys.argv[3]).upper()
amount=float(sys.argv[4])
try:
response = requests.get(f"https://api.frankfurter.app/{date}?amount={amount}&from={from_currency}&to={to_currency}")
print(f"{amount} {from_currency} is {response.json()['rates'][to_currency]} {to_currency} on {date}")
except ValueError: # includes simplejson.decoder.JSONDecodeError
print('Decoding JSON has failed')
Related
Hi I have this php code:
<?php
$firstname = htmlspecialchars($_GET["firstname"]);
$lastname = htmlspecialchars($_GET["lastname"]);
$password = htmlspecialchars($_GET["password"]);
$result['username']=$firstname;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
exit ;
?>
And this python code:
import requests
def send(firstname,lastname,password):
userdata = {"firstname": firstname, "lastname":lastname , "password": password}
resp = requests.post('http://www.example.com/php.php', params=userdata)
print ( 'Content-Type:' )
print( resp.headers['Content-Type'])
getdata = resp.json()
print (getdata[ 'username' ] )
send('yama','last','password')
My python output is:
Content-Type:
text/html
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/requests/models.py", line 971, in json
return complexjson.loads(self.text, **kwargs)
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/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)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 35, in <module>
File "<string>", line 32, in send
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/requests/models.py", line 975, in json
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
So you can see in my output that Content-Type:
text/html and it is not application/json, What should I do?
I know this question is dublicated but I tryed everything on stackoverflow answers and my codes still not working for me!
I'm using google api in python. My purpose is find and download any image similar with my image. This my error:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 971, in json
return complexjson.loads(self.text, **kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\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)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Administrator\.vscode\tempCodeRunnerFile.python", line 27, in <module>
results = response.json()["items"]
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 975, in json
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
What was wrong with my code? I noticed response was return <Response [400]>, i guess it is problem with my code. How to fix it? Any help is appreciated. Below is the code:
import requests
import urllib.request
# Replace YOUR_API_KEY with your actual API key
api_key = "YOUR_API_KEY"
# Load the image you want to search for
# image_data = open("path/to/image.jpg", "rb").read()
image_data = open("C:\\Users\\Administrator\\Downloads\\theme\\3f559715-f407-47de-8540-1cd9e4fdc56c.jpg", "rb").read()
# Send the request to the Google Search API's "similar images" feature
response = requests.post(
"https://www.googleapis.com/customsearch/v1/similar?",
params={
"key": api_key,
# "cx": "YOUR_CX_VALUE", # Replace YOUR_CX_VALUE with your actual CX value
"cx": "d47119ff66e004d6b",
},
headers={
"Content-Type": "image/jpeg",
},
data=image_data,
)
# print(response) -><Response [400]>
# Get the search results from the response
results = response.json()["items"]
# Iterate through the search results and download the images
for result in results:
image_url = result["link"]
image_filename = image_url.split("/")[-1]
urllib.request.urlretrieve(image_url, image_filename)
print(f"Downloaded image: {image_filename}")
I am trying to get data from the below seen URLs
import requests
import json
service_a = requests.get('https:xxxxx')
service_b = requests.get('https:xxxxx')
service_a.json()
service_b.json()
While for the case of service_a, service_a.json() gives me the expected data, for service_b, the call service_b.json() gives me the following error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python3/dist-packages/requests/models.py", line 892, 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())
File "/usr/lib/python3/dist-packages/simplejson/scanner.py", line 79, in scan_once
return _scan_once(string, idx)
File "/usr/lib/python3/dist-packages/simplejson/scanner.py", line 70, in _scan_once
raise JSONDecodeError(errmsg, string, idx)
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Why is this happening?
ps. I notced that when I try to visit the https link of service_a, the data it contains are shown in the browser, while for sevice_b, no data are shown in the browser, but when I click it a file with its data is downloaded in my computer.
Try to check the Content-Type of service_b response.
import csv
response = requests.get(API_URL)
decoded_data = response.content.decode("utf-8")
csv_data = csv.reader(decoded_data.splitlines(), delimiters=",")
csv_list = list(csv_data)
in most cases your
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
error is due to:
non-JSON conforming quoting
XML/HTML output (that is, a string starting with <), or
incompatible character encoding
I am uploading a file to a REST API with a Python 3 script via the windows command line. The filename is an argument passed in to the script. Everything works fine unless there is a space in the path name. i.e. c:\temp\myFolder\1.jpg works, but c:\temp\my Folder\1.jpg throws an error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The code up until the error is as follows:
def upload_photo(filename):
f = open(filename, "rb")
data = f.read()
data_md5 = hashlib.md5(data).hexdigest()
f.close()
r = requests.put('https://upload.mysite.com/{}'.format(filename), data=data)
response = json.loads(r.text)
I'm not sure how to fix it. Thanks for the help.
--Edit--
Full traceback
c:\>python test.py "c:/temp/my folder/1.jpg"
Traceback (most recent call last):
File "test.py", line 144, in <module>
print(test(sys.argv[1]))
File "test.py", line 132, in upload_photo
response = json.loads(r.text)
File "C:\Users\Default\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\Default\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Default\Default\Local\Programs\Python\Python37-32\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)
You need to encode the link properly; escaping the invalid character(s). You can do that with urllib.
>>> import urllib
>>> filename = urllib.parse.quote('c:\temp\my Folder\1.jpg')
>>> 'https://upload.mysite.com/' + filename
'https://upload.mysite.com/c%3A%09emp%5Cmy%20Folder%01.jpg'
I am trying to use python slackclient.
I am getting json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) error for this, print (slack_client.api_call("users.list")) in the below code. I tried like this, but still getting error, print (json.loads(slack_client.api_call("users.list")))
please suggest what could be wrong,
the first 2 api calls works fine and return result. only the users list api call is giving me error
print (slack_client.api_call("api.test"))
print (slack_client.api_call("auth.test"))
print (slack_client.api_call("users.list"))
Traceback (most recent call last):
File "print_bot_id.py", line 15, in <module>
print (slack_client.api_call("users.list"))
File "/Users/vt/anaconda3/lib/python3.6/site-packages/slackclient/_client.py", line 83, in api_call
result = json.loads(self.server.api_call(method, timeout=timeout, **kwargs))
File "/Users/vt/anaconda3/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/Users/vt/anaconda3/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/vt/anaconda3/lib/python3.6/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)
#smarx , curl for the users.list endpoint returns nothing, is there different end point
$ curl -X POST https://slack.com/api/api.test?token='abc'
{"ok":true,"args":{"token":"abc"}}
m-C02KL0B1FFT4:slack_bot vt$ curl -X POST https://slack.com/api/users.list?token='abc'
$