47
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python3 で Decimal を JSON に変換

Last updated at Posted at 2018-01-24

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
47
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
47
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?