본문 바로가기

trouble-shooting

TypeError: Object of type datetime is not JSON serializable

python의 json.dumps를 사용하다가 만나게 되는 에러다. json.dumps는 내부에서 JSONEncoder를 사용해서 직렬화를 하는데 해당 라이브러리에서 지원하는 타입이 아니면 에러를 발생시키기 때문인다.

가장 간단한 해결방법으로는 아래와 같이 코딩하는 방법이 있다.

json.dumps(dict_obj, default=str)

자 이제 에러가 나지 않는다. 그런데 우리가 원한 형태의 직렬화가 맞는가? 만약 아니라면 해결방법을 찾아보자. 일단 JSONEncoder는 아래와 같은 타입만 기본적으로 변환해준다.

class JSONEncoder(object):
    """Extensible JSON <https://json.org> encoder for Python data structures.

    Supports the following objects and types by default:

    +-------------------+---------------+
    | Python            | JSON          |
    +===================+===============+
    | dict              | object        |
    +-------------------+---------------+
    | list, tuple       | array         |
    +-------------------+---------------+
    | str               | string        |
    +-------------------+---------------+
    | int, float        | number        |
    +-------------------+---------------+
    | True              | true          |
    +-------------------+---------------+
    | False             | false         |
    +-------------------+---------------+
    | None              | null          |
    +-------------------+---------------+

그리고 해당 위 명시되지 않은 타입에 대해서는 default파라미터에 입력된 함수를 통해 변환시켜 주는 것이다. 따라서 default에 해당하는 함수만 잘 만들어주면 해결 될 것이라는 걸 알 수 있다.

import json
from datetime import datetime as dt

test_dict = {
    'now': dt.now(),
}

def default_encode(obj):
    return obj.strftime('%Y%m%d%H%M%S')

text = json.dumps(test_dict, default=default_encode)
print(text)