개발학습일지

[Restfull API] TypeError : Object of type ... is not JSON serializable 에러가 발생한 이유와 해결 방법 본문

Restful API

[Restfull API] TypeError : Object of type ... is not JSON serializable 에러가 발생한 이유와 해결 방법

처카푸 2024. 5. 21. 13:44

TypeError : Object of type ... is not JSON serializable 에러가 발생한 이유와 해결 방법

 

문제 발생

: DB에 있는 데이터를 서버에 select 하는 중,

" TypeError: Object of type datetime is not JSON serializable" 발생

TypeError

 

발생 이유

: 에러를 해석하면, 데이터를 JSON으로 변환 할 수 없다 라는 뜻이다.

: JSON은 문자열 또는 숫자만 사용하기 때문에,

  이 에러의 이유는 내가 보내는 데이터에 문자 숫자 외에 다른 것이 있다는 말이다.

 

 

해결 방법

: 나의 데이터를 print() 함수로 확인하고 문자 또는 숫자를 제외한 다른 형태가 있다면 문자열로 바꿔 주면 된다.

: connsection.cursor() 에 dictionary=True를 넣어주면,

  커서 유형을 사전으로 반환해주기 때문에

  JSON으로 변환하는데 문제가 있던 형태의 데이터를 문자열로 변환해준다.

: MySQLConnection.cursor() 메소드 설명 사이트

https://docs.oracle.com/cd/E17952_01/connector-python-en/connector-python-api-mysqlconnection-cursor.html

 

10.2.6 MySQLConnection.cursor() Method

10.2.6 MySQLConnection.cursor() Method Syntax: cursor = cnx.cursor([arg=value[, arg=value]...]) This method returns a MySQLCursor() object, or a subclass of it depending on the passed arguments. The returned object is a cursor.CursorBase instance. For mor

docs.oracle.com

# select API 중 일부분
try : 
            connection = get_connection()

            query = '''
                    select *
                    from recipe
                    limit '''+offset+''', '''+limit+''';
                    '''
            # 데이터에 문자, 숫자를 제외한 다른 형태가 있어서 
            # dictionary=True 를 작성해서 변환해준다.
            cursor = connection.cursor(dictionary=True)

            cursor.execute( query )

            result_list = cursor.fetchall()

            # 프린트 함수로 나의 데이터 확인
            print(result_list)

            cursor.close()
            connection.close()

 

 

해결 완료

: 수정하고 포스트맨에서 결과를 확인해보니, 잘 가져온 것을 확인 할 수 있었다!!

Postman Send