AWS の DynamoDB では、Decimal という型が使われます。この型を JSON に変換する方法です。
変換できない例
error.py
#! /usr/bin/python
#
import json
from decimal import Decimal
# ----------------------------------------------------------------
aa = [Decimal(3.4),Decimal(5.3)]
json_str = json.dumps(aa)
print(json_str)
# ----------------------------------------------------------------
実行結果
$ ./error.py
Traceback (most recent call last):
File "./error.py", line 8, in <module>
json_str = json.dumps(aa)
File "/usr/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable
ちゃんと変換できる例
ok.py
#! /usr/bin/python
#
import json
from decimal import Decimal
# ----------------------------------------------------------------
def decimal_default_proc(obj):
if isinstance(obj, Decimal):
return float(obj)
raise TypeError
# ----------------------------------------------------------------
aa = [Decimal(3.4),Decimal(5.3)]
json_str = json.dumps(aa,default=decimal_default_proc)
print(json_str)
# ----------------------------------------------------------------
実行結果
$ ./ok.py
[3.4, 5.3]
確認したバージョン
$ python --version
Python 3.7.2