본문 바로가기
python

TypeError: Object of type ndarray is not JSON serializable

by 타닥타닥 토다토닥 부부 2024. 7. 31.
반응형

TypeError: Object of type ndarray is not JSON serializable

 

1. 오류설명

- 파이썬 딕셔너리를 json파일로 저장할때, array이가 포함되어 있다면 발생하는 오류 입니다.

import json
import numpy as np

y = np.array([3,4])

dict = {
    "name" : "John",
    "array" : y
}
with open("temp.json", 'w') as f:
    json.dump(dict, f)

 

TypeError: Object of type ndarray is not JSON serializable

 

2. 해결방법

-  array를 list로 변경하면 문제없이 저장 됩니다.

-  tolist() 메서드를 활용하여 array를 리스트로 변경합니다.

import json
import numpy as np

y = np.array([3,4])

### tolist() 메서드를 활용하여 array를 리스트로 변경합니다.
y = y.tolist()

dict = {
    "name" : "John",
    "array" : y
}
with open("temp.json", 'w') as f:
    json.dump(dict, f)
반응형

댓글