首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何捕捉json.decoder.JSONDecodeError?

如何捕捉json.decoder.JSONDecodeError?
EN

Stack Overflow用户
提问于 2020-06-27 19:17:27
回答 1查看 207关注 0票数 0

我的程序没有捕获json json.decoder.JSONDecodeError,尽管我已经编写了捕获这些错误的代码(参见try-except block)。我做错了什么?

错误码:

代码语言:javascript
复制
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我的代码:

代码语言:javascript
复制
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次之后

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-27 19:24:40

因为您需要在将响应转换为json时放置try子句,而不是在读取时。

使用下面的代码:

代码语言:javascript
复制
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 status
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62609264

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档