Skip to content

Instantly share code, notes, and snippets.

@kennovation1
Created May 2, 2019 20:58
Show Gist options
  • Save kennovation1/c5d422a5b280ef4371cec0ccd1892b8c to your computer and use it in GitHub Desktop.
Save kennovation1/c5d422a5b280ef4371cec0ccd1892b8c to your computer and use it in GitHub Desktop.
Decimal encoder to use with json.dumps so that it handles Decimals (by converting them to floats)
class DecimalEncoder(json.JSONEncoder):
'''
An encoder for use with json.dumps when the dict contains Decimal type objects
such as are returned for DynamoDB number attributes.
Usage: json.dumps(someDict, cls=DecimalEncoder)
'''
def default(self, o):
if isinstance(o, decimal.Decimal):
return float(o)
return super(DecimalEncoder, self).default(o)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment