Skip to content

Error in Lambda function datetime is not JSON serializable

0

Im trying to run the following code to fetch data from Redshift data but in Redshift Im getting the following error:

SQL Error [XX000]: ERROR: Error in AWS Lambda function execution: {"errorMessage": "Object of type datetime is not JSON serializable", "errorType": "TypeError", "requestId": "xx", "stackTrace": ["  File \"/var/task/lambda_function.py\", line 29, in
  Detail: 
  -----------------------------------------------
  error:  Error in AWS Lambda function execution: {"errorMessage": "Object of type datetime is not JSON serializable", "errorType": "TypeError", "requestId": "xx", "stackTrace": ["  File \"/var/task/lambda_function.py\", line 29, in
  code:      32001
  context:   Please check Cloudwatch logs of the Lambda function for error details
  query:     0
  location:  exfunc_client.cpp:157
  process:   padbmaster [pid=1073800171]
  -----------------------------------------------

Of course I already replaced the cluster_name, database_name, secret arn with ours.

import json
import boto3

def lambda_handler(event, context):
    
    client = boto3.client('redshift-data') 
    CLUSTER_NAME='test-db-cluster'
    DATABASE_NAME='test-db'
    SECRET='arn:aws:secretsmanager:your-region:your-accountid:secret:sample-secret'
    STATEMENT_NAME='test-sql'

    SQL = '''
        SELECT 1;
    '''
    res = client.execute_statement(
        ClusterIdentifier=CLUSTER_NAME,
        Database=DATABASE_NAME,
        SecretArn=SECRET,
        StatementName=STATEMENT_NAME,
        Sql=SQL,
        WithEvent=True
    )
    print(json.dumps(res))

and here is how I set it up and invoke it in Redshift:

CREATE OR REPLACE EXTERNAL FUNCTION udf_lambda_lookup ()
RETURNS varchar STABLE
LAMBDA 'function_name_here'
IAM_ROLE  'arn iam role here';
select udf_lambda_lookup ()

asked 2 years ago1.2K views

1 Answer
1

The error you're encountering is due to the Lambda function trying to serialize a datetime object to JSON, which is not directly supported. This typically happens when you're trying to return or log an object that contains datetime values.

To resolve this issue, you need to modify your code to handle datetime serialization. Here are a few approaches you can take:

  1. Use a custom JSON encoder: Create a custom JSON encoder that can handle datetime objects. You can do this by subclassing json.JSONEncoder and defining how to serialize datetime objects.

    import json
    from datetime import datetime
    
    class DateTimeEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, datetime):
                return obj.isoformat()
            return super().default(obj)
    
    # Then use it when dumping to JSON
    json.dumps(res, cls=DateTimeEncoder)
  2. Convert datetime objects to strings before serialization: If you know which fields contain datetime objects, you can convert them to strings before serializing.

    def datetime_to_string(obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return obj
    
    # Apply this function to your result before serializing
    serializable_res = json.loads(json.dumps(res, default=datetime_to_string))
    print(json.dumps(serializable_res))
  3. Use a library like simplejson: The simplejson library can handle datetime serialization out of the box.

    import simplejson as json
    print(json.dumps(res, ignore_nan=True))

Remember to handle the datetime serialization before returning the response from your Lambda function or when logging the response. Also, make sure you're using compatible versions of boto3 and other dependencies in your Lambda environment.

Lastly, it's a good practice to wrap your main logic in a try-except block to catch and log any errors, which can help with debugging:

try:
    res = client.execute_statement(...)
    print(json.dumps(res, cls=DateTimeEncoder))
except Exception as e:
    print(f"An error occurred: {str(e)}")
    raise

This will ensure that any errors are properly logged in CloudWatch, making it easier to diagnose issues in your Lambda function.
Sources
Handle Lambda errors in API Gateway - Amazon API Gateway
error trying to parse event from API HTTP integration in lambda Python 3.12 runtime | AWS re:Post
Using CloudWatch Logs with Lambda - AWS Lambda
Log and monitor Node.js Lambda functions - AWS Lambda

answered 2 years ago

EXPERT

reviewed 2 years ago

EXPERT

reviewed 2 years ago

EXPERT

reviewed 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.