[Python] TypeError: Object of type int32 is not JSON serializable

2020. 3. 16. 14:38오류

from collections import defaultdict

data = []

for i in range(len(medical_df)):

    group_data = defaultdict()
    bad_effect = defaultdict()

    bad_effect["alchol"] = medical_df['alchol'][i]
    bad_effect["combination_ban"] = medical_df['combinataion_ban'][i]
    bad_effect["dur_ban"] = medical_df['부작용'][i]
    bad_effect["bad_effect"] = medical_df['bad_effect'][i]

    group_data["item_code"] = medical_df['item_code'][i]
    group_data["medicine_name"] = medical_df['medicine_name'][i]
    group_data["save_method"] = medical_df['save_method'][i]
    group_data["valid_date"] = medical_df['valid_dates'][i]
    group_data["bad_effect"] = bad_effect

    data.append(group_data)

 

 

dataframe 에서 json파일로 변경시 아래와 같은 오류가 난다면
TypeError: Object of type int32 is not JSON serializable

 

import numpy as np

class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(NpEncoder, self).default(obj)

m_json = json.dumps(data, ensure_ascii=False, indent="\t", cls=NpEncoder)

 

NpEncoder함수를 생성하여 json파일로 만들 수 있다.

728x90