1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Error json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) on...

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024 às 11:22.

  1. Stack

    Stack Membro Participativo

    The problem is the following:

    I make a request through the requests class, like this:

    payload = {"offset":0,"limit":10}
    headers = {'content-type': 'application/json','Accept': 'application/json'}
    response = requests.post(url, data=json.dumps(payload), headers=headers)


    I get a successful response, in the form I expect:

    result = response.content


    b'[{"id":12467458,"key":"119b21eabde78592944ef768", ...}]

    type(a)


    <class 'bytes'>

    I try to get the response as a list of dictionaries:

    data_list = response.json()


    [{'id': 12467458, 'key': '119b21eabde78592944ef768', ...}]

    type(data_list)


    <class 'list'>

    And up to this point everything is fine. The problem is that even though I apparently get the list I need, the code gives me the following error:


    json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

    If I stop the code to display what the variable in question contains, it doesn't throw any error, even though the ‘print’ is a few lines below the line where the error starts. However, if I let the code run, it drops the error and stops the code.

    I've tried other way but it also have failed:

    data = response.content
    string_list = data.decode('utf-8','ignore')
    data_list = json.loads(string_list) # Fails here with the same error


    I have also tried other things like:

    • filtering the data (once I have converted it into a list) and dumping it into another variable, then deleting the ‘problematic’ variable.
    • create a text file, dump the response obtained in the request and then open the file again and work with the data.

    I keep getting the same error.

    Apart from the error itself, there is one thing I don't understand and that is that I can work with the data (once I have obtained it as a list) but I get the error in the ‘json.loads()’ or ‘response.json()’, being these lines higher up in the code.

    I would be grateful for any help.

    Thank you in advance.

    Continue reading...

Compartilhe esta Página