[Python] Solve "RequestsJSONDecodeError" & "UnicodeDecodeError" while parsing API...

Discussão em 'Python' iniciado por Stack, Janeiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I'm calling a GET API , and is trying to parse the API response-body in JSON format. I have below approaches for parsing, i am mentioning the code and the traceback below:

    Code_Snippet(Approach 1):

    response=requests.get(loginapi,headers=headers)
    print(response.json())

    ----And then I tried-----

    response=requests.get(loginapi,headers=headers)
    print(json.loads(response.text)


    Traceback(same for both approaches):

    RequestsJSONDecodeError: Expecting value: line 1 column 1 (char 0)


    Code_Snippet(Approach 2):

    print("Response Encoding: ",response.encoding) --Returns 'utf-8'
    respData= json.loads(response.content.decode('utf-8'))
    print(respData)


    Traceback:

    Response Encoding: utf-8
    UnicodeDecodeError: 'utf-8' codec can't decode byte...: invalid start byte


    For reference below is the response JSON which i beautified from postman:

    {
    "id": 188798,
    "token": "e5f38c96-d25a-47hjo03-bb06-ec064yruu2eff84",
    "display_name": "Abhijeet Goswami",
    "email": "abhijeet.goswami@live.com",
    "permissions": [
    6,
    10,
    110
    ],
    "rcs_code": null,
    "irm_code": null,
    "branch_id": null
    }


    **Kindly help in suggesting a solution to cope-up this and parse the response :)

    Continue reading...

Compartilhe esta Página