genovese
genovese

Reputation: 55

How to catch json.decoder.JSONDecodeError?

My program, is not catching json json.decoder.JSONDecodeError, Although i have write the code to catch these errors (see the try-except block). what i am doing wrong?

Error code:

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

My code:

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

I get the DecodeError randomly, sometimes after 2-3 tries, sometimes after 12-13

Upvotes: 2

Views: 4660

Answers (1)

Astik Gabani
Astik Gabani

Reputation: 605

Because you need to put the try clause while converting the response to json, not at the reading time.

Use below Code:

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

Upvotes: 1

Related Questions