pythonaws-lambda

"errorMessage": "'NoneType' object is not iterable"


its an aws lambda function

   try:
       with  urllib.request.urlopen(api_url) as response:
           data=json.loads(response.read().decode())
           print(json.dumps(data, indent = 4 ))
   except Exception as e :
       print(f"error reading data : {e} ")
       return {"statuscode":"500","body":"Error fetching data"}

   games_messages = [game_format(game) for game in data]

the error that I get :

  "errorMessage": "'NoneType' object is not iterable",
  "errorType": "TypeError",
  "requestId": "11a9a46e-3abe-4f6e-8c38-278c0697238a",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 69, in lambda_handler\n    games_messages = [game_format(game) for game in data]\n",
    "  File \"/var/task/lambda_function.py\", line 15, in game_format\n    quarter_scores = ', '.join([f\"Q{q['Number']}: {q.get('AwayScore', 'N/A')}-{q.get('HomeScore', 'N/A')}\" for q in quarters])\n"
  ]
}

the data that I fetched:

enter image description here


Solution

  • The issue is not originating from the code block you provided, rather it is originating from line 15:

    quarter_scores = ', '.join([f"Q{q['Number']}: {q.get('AwayScore', 'N/A')}-{q.get('HomeScore', 'N/A')}" for q in quarters])
    

    Error message states quarters is None.

    Indeed, in the data you fetched, quarters is null, (json.loads function turns null into None)

    enter image description here

    Solution:

    before iterating, make sure quarters is not None.