Reputation: 71
I have a POST request and it returns a JSON. If the user is searching for something what is does not exist, then the JSON is empty. How can I avoid the error message and print something like: 'no results' ?
The error message:
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s) File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.7/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)
The code: // It works well, except if the return JSON is empty //
import requests
import json
from private import payload, criterias
r = requests.session()
url_login = 'https://somesite.com/login.php'
url_search = 'https://somesite.com/data.php?jsons=true'
req1 = r.post(url_login, data=payload)
req2 = r.post(url_search, data=criterias)
data = json.loads(req2.text)
release = 'release_name'
for release in data['results']:
print(release['release_name']
Upvotes: 0
Views: 696
Reputation: 8405
You asked how to avoid JSONDecodeError
. The answer is to catch it.
import requests
import json
from private import payload, criterias
r = requests.session()
url_login = 'https://somesite.com/login.php'
url_search = 'https://somesite.com/data.php?jsons=true'
req1 = r.post(url_login, data=payload)
req2 = r.post(url_search, data=criterias)
try:
data = json.loads(req2.text)
release = 'release_name'
for release in data['results']:
print(release['release_name']) # your code did not have a close parentheses
except ValueError as e: # catches subclass JSONDecodeError
print("No results")
print(f"req.text={req.text}")
print(e)
Upvotes: 1