1

I am using python 3.6 and connecting to dynamodb to fetch data. Getting above error on line json.dumps(item, indent=4, cls=DecimalEncoder) Any suggestions what I am doing wrong.

import json
import boto3
import decimal

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MY_TABLE')

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

def lambda_handler(event, context):
    # TODO implement
    category_id = event["queryStringParameters"]["id"]
    response = table.get_item(
        Key={
            'category': category_id
            }
           )    

    item = response['Item']
    return {
     "isBase64Encoded": False,
     "statusCode": '200',
     "headers": {},
     "body": json.dumps(item, indent=4, cls=DecimalEncoder)
            }

1 Answer 1

3

JSON does not support sets so you should make your customer decoder for json.dumps able to convert sets to lists:

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, set):
            return list(o)
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @blhsing, I modified my customer decoder and it decoded set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.