1

I am getting this error : TypeError: Object of type set is not JSON serializable

when I am wrtting this code: response['body'] = json.dumps(body,cls=CustomEncoder)

The function code is:

def getPartner(partner_id,gender):
    response = table.get_item(
        Key={
            'partner_id': partner_id,
            'gender': gender
        }
    )
    return buildResponse(200,response['Item'])
        
def buildResponse(statusCode, body=None):
    response = {
        'statusCode' : statusCode,
        'headers': {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin':'*'
        }
    }
    if body is not None:
        response['body'] = json.dumps(body,cls=CustomEncoder)
    return response

Here CustomEncoder is a class as follows:

class CustomEncoder(json.JSONEncoder):
    def default(self,obj):
        if isinstance(obj,Decimal):
            return float(obj)
        return json.JSONEncoder.default(self,obj)

So what should I do to serialize the data in body.

nsb
  • 95
  • 1
  • 4

1 Answers1

1

body probably contains a set; which the JSON format doesn't support - you probably want to make it a list (or a dict with null keys), perhaps indicating with another field that it's intended to be a set

>>> import json
>>> json.dumps(set((1,2,3)))
Traceback (most recent call last):
[..]
TypeError: Object of type set is not JSON serializable
>>> json.dumps(list(set((1,2,3))))
'[1, 2, 3]'
>>> json.dumps({k:None for k in set((1,2,3))})
'{"1": null, "2": null, "3": null}'
>>> json.dumps(f"set:{set((1,2,3))}")  # coerce to string
'"set:{1, 2, 3}"'
ti7
  • 16,375
  • 6
  • 40
  • 68