Programing

Python에서 JSON을 직렬화 할 때 "TypeError : (정수)를 JSON 직렬화 할 수 없습니다"?

crosscheck 2020. 6. 24. 07:40
반응형

Python에서 JSON을 직렬화 할 때 "TypeError : (정수)를 JSON 직렬화 할 수 없습니다"?


파이썬에서 json 파일로 간단한 사전을 보내려고하는데 "TypeError : 1425 is JSON serializable"메시지가 계속 나타납니다.

import json
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8'))
afile.close()

기본 인수를 추가하면 쓰지만 정수 값은 json 파일에 문자열로 기록되므로 바람직하지 않습니다.

afile.write(json.dumps(alerts,encoding='UTF-8',default=str))

내 문제를 찾았습니다. 문제는 내 정수가 실제로 type이라는 것 numpy.int64입니다.


파이썬 3에서 numpy.int64를 json 문자열로 덤프하는 데 문제가있는 것으로 보이며 파이썬 팀은 이미 그것에 대해 대화를하고 있습니다. 자세한 내용은 여기를 참조 하십시오 .

Serhiy Storchaka가 제공하는 해결 방법이 있습니다. 잘 작동하므로 여기에 붙여 넣습니다.

def convert(o):
    if isinstance(o, numpy.int64): return int(o)  
    raise TypeError

json.dumps({'value': numpy.int64(42)}, default=convert)

이것은 나를 위해 문제를 해결했습니다.

def serialize(self):
    return {
        my_int: int(self.my_int), 
        my_float: float(self.my_float)
    }

숫자를 int64(numpy에서) 로 변환하십시오 int.

예를 들어 variable x이 int64 인 경우 :

int(x)

int64의 배열 인 경우 :

map(int, x)

또는 먼저 객체를 데이터 프레임으로 변환 할 수 있습니다.

df = pd.DataFrame(obj)

다음이 저장 dataframeA의 json파일 :

df.to_json(path_or_buf='df.json')

도움이 되었기를 바랍니다


Numpy Data Type이 있습니다. 정상 int () 또는 float () 데이터 유형으로 변경하십시오. 잘 작동합니다.

참고 : https://stackoverflow.com/questions/11942364/typeerror-integer-is-not-json-serializable-when-serializing-json-in-python

반응형