This rule raises an issue when AWS Lambda handlers return values that are not JSON serializable.
For synchronous AWS Lambda invocations, like via API Gateway or direct SDK calls, the value returned by the handler is automatically serialized
into a JSON string before being sent back in the response. If the return value contains objects that are not native JSON types like
datetime objects, sets, or custom class instances, the serialization will fail, causing a TypeError. This will prevent the
Lambda from returning a valid response to the client.
Convert non-JSON-serializable objects to their string representation or to JSON-serializable types before returning them:
datetime objects: Convert to ISO format strings using .isoformat() list(set_object) __dict__ field, dataclasses.asdict(…) for dataclasses or
a custom todict() method. See the following examples for more details on how to handle custom classes:
import json
import dataclasses
# A custom class representing a user
@dataclasses.dataclass
class User:
name: str
age: int
def to_dict(self) -> dict:
return { "name": self.name, "age": self.age }
user = User("Alice", 30)
# Method 1: Using __dict__ field
json.dumps(user.__dict__)
# Method 2: Using dataclasses.asdict()
json.dumps(dataclasses.asdict(user))
# Method 3: Using custom to_dict() method
json.dumps(user.to_dict())
import datetime
def lambda_handler(event, context):
return {
"message": "Request processed successfully",
"timestamp": datetime.datetime.now() # Noncompliant: not JSON serializable
}
import datetime
def lambda_handler(event, context):
return {
"message": "Request processed successfully",
"timestamp": datetime.datetime.now().isoformat() # Compliant: converted to string
}