bdart
bdart

Reputation: 755

AWS Lambda python custom response encoding

When you query data with your lambda function from dynamodb and there are binary types or decimal/number types in it my default setup below prompts with an JSONEncoding Error that he cannot deal with Binary or Decimal. I can work around with a small piece of code that I attach to json.dumps(data, indent=2, cls=JSONEncoder)

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

But using json.dumps() in front of your return statement double json format the response and that leads to escaped signs. To repeat the problem just return data prompts with the mentioned error.

How can I affect my return statement that converts to json?

UPDATE:

The problem is solved dirty by manually change the items with:

test = operations['Items'][0]
test['id'] = float(test['id'])

But this seems messy.

Upvotes: 3

Views: 1849

Answers (1)

Eric Horne
Eric Horne

Reputation: 113

I'm assuming you are looking to return from the lambda handler function. If so, while not elegant, you can do this:

json.loads(json.dumps(value, cls=JSONEncoder))

Not awesome because eventually Lambda will convert that structure back into a string (not sure if there's a way to just skip the intermediate step of converting to a python structure).

Upvotes: 3

Related Questions