๊ด€๋ฆฌ ๋ฉ”๋‰ด

ruriruriya

[RESTful API] Python Flask - TypeError: Object of type Decimal is not JSON serializable ์—๋Ÿฌ ํ•ด๊ฒฐ ๋ณธ๋ฌธ

๐ŸžDebugging Story

[RESTful API] Python Flask - TypeError: Object of type Decimal is not JSON serializable ์—๋Ÿฌ ํ•ด๊ฒฐ

๋ฃจ๋ฆฌ์•ผใ…‘ 2023. 12. 13. 09:16
๋ฐ˜์‘ํ˜•

TypeError: Object of type Decimal is not JSON serializable ์—๋Ÿฌ ํ•ด๊ฒฐ

RESTful API ๋งŒ๋“ค ๋•Œ GET ๋ฐฉ์‹์˜ API ํ•จ์ˆ˜์—์„œ 
'๋ฐ์ดํ„ฐ ํƒ€์ž… ์ง๋ ฌํ™”'๋ผ๋Š” ์—๋Ÿฌ๊ฐ€ ๋‚ฌ๋‹ค.

 

์›์ธ

๊ทธ๋ž˜์„œ MySQL์—์„œ ์†Œ์ˆ˜์ ์„ JSON์œผ๋กœ ๊ฐ€์ ธ์˜ค์ง€ ๋ชปํ•  ๋•Œ ๋‚˜๋Š” ์—๋Ÿฌ๋ผ๊ณ  ๋‹ค๋ฅธ ๋ธ”๋กœ๊ทธ์—์„œ ๋ดค๋‹ค.
๊ทธ๋ž˜์„œ ๊ทธ ์†Œ์ˆ˜์  ์žˆ๋Š” ์ปฌ๋Ÿผ์„ ์ œ์™ธํ•˜๊ณ  ๋‹ค์‹œ ํ•ด๋ณด๋‹ˆ ๋™์ž‘ํ–ˆ๋‹ค.

ํ•ด๊ฒฐ๋ฐฉ๋ฒ• 01

ํ•ด๊ฒฐ๋ฐฉ๋ฒ•์€ ์„ฑ๊ณต ์‹œ ๋ฆฌํ„ดํ•  ๋•Œ items์˜ ๊ฒฐ๊ณผ ๊ฐ’์„ str๋กœ ํ•œ๋ฒˆ ์”Œ์šฐ๋Š” ๊ฒƒ์œผ๋กœ ํ•ด๊ฒฐ์ด ๋˜์—ˆ๋‹ค....
์ข‹์€ ํ•ด๊ฒฐ๋ฐฉ๋ฒ•์ธ์ง€๋Š” ์ž˜ ๋ชจ๋ฅด๊ฒ ๋‹ค.

        return {'result' : 'success',
                'items':str(result_list),
                'count': len(result_list)}, 200

 

ํ•ด๊ฒฐ๋ฐฉ๋ฒ• 02

๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์œผ๋กœ๋Š” ํ•ด๋‹น ๋ณ€์ˆ˜ ๋ถ€๋ถ„์„ print ํ•ด์„œ ๋ณด๋Š” ๊ฒƒ์ด๋‹ค.
'rating_avg'๋ฅผ ๋ณด๋‹ˆ Decimal(-) ์ด๋ ‡๊ฒŒ ๋‚˜์™€์„œ ๋ฌธ์ž๋‚˜ ์ˆซ์ž๋กœ ๋ณด์ด์ง€ ์•Š์•„ ๋ฐœ์ƒํ•˜๋Š” ๊ฒƒ์ด์—ˆ๋‹ค.

{'id': 3, 'title': 'Babes in Toyland', 'summary': 'Curabitur convallis. Duis consequat dui nec
nisi volutpat eleifend. Donec ut dolor.', 'imageUrl': None, 'genre': 'Children|Fantasy|Musical',
'year': '2003-05-06T00:00:00', 'attendance': 79006, 'createdAt': '2023-12-04T07:37:10', 
'rating_avg': Decimal('4.5000'), 'review_cnt': 4}
127.0.0.1 - - [13/Dec/2023 09:50:58] "GET /movie/3 HTTP/1.1" 500 -

ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์€ Decimal์„ float ์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ๋ฉด์„œ ํ•ด๊ฒฐ์ด ๋˜์—ˆ๋‹ค.

            i = 0
            for row in result_list :
                result_list[i]['rating_avg']= float(row['rating_avg'])
                # TypeError: Object of type Decimal is not JSON serializable
                i = i + 1

 

๋ฐ˜์‘ํ˜•