5
3

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.

pythonでdate, datetime型を含むlistやdictをjson文字列に変換する

Posted at

json.dumpsで発生するエラー:sob:

import json
from datetime import datetime

test = [datetime.now()]
json.dumps(test)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 244, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2018, 8, 28, 2, 52, 36, 329332) is not JSON serializable

何も考えずに実行すると上記のエラーが発生します。
datetime型の項目を含んだ状態でjson.dumpsで文字列に変換しようとすると、シリアライズが出来ないというエラーが!

シリアライズできない項目を考慮した設定を追加してから実行:stuck_out_tongue_closed_eyes:

import json
from datetime import date, datetime

test = [datetime.now()]

def sugoi_json_dumps(json_obj):
    def json_serial(obj):
        # 日付型の場合には、文字列に変換します
        if isinstance(obj, (datetime, date)):
            return obj.isoformat()
        # 上記以外はサポート対象外
        raise TypeError("Type %s not serializable" % type(obj))
    return json.dumps(json_obj, default=json_serial)

sugoi_json_dumps(test)
'["2018-08-28T02:57:02.747438"]'

と、こんな感じで表示されてくれます。
json.dumpsのdefaultに関数を渡してあげればOKです:ok_hand:

最後に

株式会社ネコカリでは猫の手も借りたい🔥炎上中🔥なお仕事を募集しています!
一緒に働くメンバーも募集していますので、よかったら是非!

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?