Python Forum
Empty response to request causing .json() to error
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Empty response to request causing .json() to error
#1
I have a problem with my code in that the response to my API request is occasionally coming back empty, which causes .json() to error out, as it expects a value.

I need to add some checking to my code, but my attempts so far have failed.

My original line was:

response=requests.get(url + id, headers=h, params=p).json()
But I need to add a check to make sure response.content is not empty... so I tried something like this:

    response=requests.get(url + id, headers=h, params=p)
    if response.content == '':
        return
    else:
        response=response.content
        response=json.loads(response)
However, responses containing empty strings continue to make it through!
What am I doing wrong here? How can I check to ensure that if response.content is empty, then do nothing and continue on through the function?
Reply
#2
Why not just catch the error?

try:
    response = json.loads(response)
except json.decoder.JSONDecodeError:
    response = ""  # or return or whatever you want to do on a failed decode.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  json loads throwing error mpsameer 8 677 Jan-23-2024, 07:04 AM
Last Post: deanhystad
  Receiving this error in my "response" and causes script to return wrong status cubangt 18 2,036 Aug-13-2023, 12:16 AM
Last Post: cubangt
  Response.json list indices must be integers or slices, not str [SOLVED] AlphaInc 4 6,362 Mar-24-2023, 08:34 AM
Last Post: fullytotal
  json decoding error deneme2 10 3,607 Mar-22-2023, 10:44 PM
Last Post: deanhystad
  Name not found in response json NewbiePyt 4 1,058 Dec-29-2022, 11:12 AM
Last Post: buran
  python requests library .JSON() error mHosseinDS86 6 3,400 Dec-19-2022, 08:28 PM
Last Post: deanhystad
  Read nested data from JSON - Getting an error marlonbown 5 1,355 Nov-23-2022, 03:51 PM
Last Post: snippsat
  request.get to read large response pythonlearner1 7 3,151 Apr-05-2022, 08:21 PM
Last Post: pythonlearner1
  how can I correct the Bad Request error on my curl request tomtom 8 5,058 Oct-03-2021, 06:32 AM
Last Post: tomtom
  string.format() suddenly causing errors with google drive API zwitrader 0 1,753 Jun-28-2021, 11:38 PM
Last Post: zwitrader

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020