我的程序没有捕获json json.decoder.JSONDecodeError,尽管我已经编写了捕获这些错误的代码(参见try-except block)。我做错了什么?
错误码:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)我的代码:
def check_code():
url = get_url()
headers = {'Accept': 'application/json'}
response = requests.get(url, headers=headers).json()
print(response)
try:
if (account := response.get('account')) and account.get('active'):
status = "active account "
else:
status = "not active account "
except (JSONDecodeError, json.JSONDecodeError):
pass
return status我随机得到DecodeError,有时在2-3次尝试之后,有时在12-13次之后
发布于 2020-06-27 19:24:40
因为您需要在将响应转换为json时放置try子句,而不是在读取时。
使用下面的代码:
def check_code():
url = get_url()
headers = {'Accept': 'application/json'}
try:
response = requests.get(url, headers=headers).json()
print(response)
except (JSONDecodeError, json.JSONDecodeError):
pass
if (account := response.get('account')) and account.get('active'):
status = "active account "
else:
status = "not active account "
return statushttps://stackoverflow.com/questions/62609264
复制相似问题