0
import boto3

client = boto3.client('cognito-idp')


def lambda_handler(event,context):
    response = client.list_users(
        UserPoolId='us-east-1_TIzqd0Fik',

    )

    return response

i want all users from cognito through API. But i am getting this error "Object of type datetime is not JSON serializable"

luk2302
  • 55,258
  • 23
  • 97
  • 137
  • Does this answer your question? [AWS Lmbda TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable](https://stackoverflow.com/questions/35574243/aws-lmbda-typeerror-datetime-datetime2012-8-8-21-46-24-862000-is-not-js) – luk2302 Nov 23 '22 at 16:26
  • Unfortunately you cannot just return the response from every AWS API directly. boto3 parses datetimes in the response from the actual service and the result is a python object that is no longer json serializable using the default json serializer. – luk2302 Nov 23 '22 at 16:27

1 Answers1

0

Try setting the default parameter of dumps to str.

default is a function applied to objects that aren't serializable. In this case it's str, so it just converts everything it doesn't know to strings. Which is great for serialization but not so great when deserializing (hence the "quick & dirty") as anything might have been string-ified without warning, e.g. a function or numpy array.

import boto3
import json

client = boto3.client('cognito-idp')


def lambda_handler(event,context):
    response = client.list_users(
        UserPoolId='us-east-1_TIzqd0Fik',

    )

    return json.dumps(response, default=str))
L Myring
  • 31
  • 6
  • 1
    While this code snippet may be the solution, including a detailed explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Shawn Hemelstrand Feb 26 '23 at 04:15
  • 1
    Yeah, fair point @ShawnHemelstrand, I was in a rush and just thought I'd quickly post a solution. Not massively helpful. Will update the answer asap – L Myring Feb 27 '23 at 09:05