Harry
Harry

Reputation: 15

Object of type 'set' is not JSON serializable

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)
            }

Upvotes: 1

Views: 6965

Answers (1)

blhsing
blhsing

Reputation: 107040

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)

Upvotes: 3

Related Questions