For example, if you handle int / float numerical data in DynamoDB, the data will be retrieved as decimal. When I run python's standard json.dumps on queries and get items that contain such data, I get an exception due to the unconvertible type. So, I always forget how to deal with this, so I will leave a note. (Similar and similar happens with Datetime type) If json.dumps fails with a type error, you can deal with it by preparing a conversion function.
You can specify default as an argument to json.dumps. By setting the conversion function here, you can handle the non-target type by yourself and convert it to your favorite type. Excerpt from the official below
If you specify> default, specify a function, and this function will be called for objects that cannot be serialized otherwise. The function must either return the object in a JSON-encoded version or raise a TypeError. If not specified, TypeError will be thrown.
Prepare a conversion function.
from decimal import Decimal def decimal_to_int(obj): if isinstance(obj, Decimal): return int(obj)
When running json.dump
Just set the conversion function in the default argument.
This time, I only wrote to convert decimal, but if you prepare the type check and conversion logic expected for the type conversion function, it is possible to support multiple types. For example, datetime is returned as a string formatted with strftime. So, it would be useful if you could understand the structure of the functions that you use for granted. So, if you want to understand it properly, please check here.
It's a very short article, but I always forget it, so it's almost my own memo.
simplejson seems to support many types. I have never used it. If you want to use it with AWS Lambda, it is not included in the standard package, so [Add it to the package yourself](https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/python-package. You need to register as [html) or Lambda layer.