programing

Python - TypeError: 'int64' 유형의 개체는 JSON 직렬화할 수 없습니다.

mailnote 2023. 6. 15. 22:01
반응형

Python - TypeError: 'int64' 유형의 개체는 JSON 직렬화할 수 없습니다.

저는 매장 이름과 일일 매출 수를 저장하는 데이터 프레임을 가지고 있습니다.아래 파이썬 스크립트를 사용하여 Salesforce에 삽입하려고 합니다.

그러나 다음 오류가 발생합니다.

TypeError: Object of type 'int64' is not JSON serializable

아래에는 데이터 프레임의 보기가 있습니다.

Storename,Count
Store A,10
Store B,12
Store C,5

저는 다음 코드를 사용하여 Salesforce에 삽입합니다.

update_list = []
for i in range(len(store)):
    update_data = {
        'name': store['entity_name'].iloc[i],
        'count__c': store['count'].iloc[i] 
    }
    update_list.append(update_data)

sf_data_cursor = sf_datapull.salesforce_login()
sf_data_cursor.bulk.Account.update(update_list)

위의 마지막 줄이 실행되면 오류가 발생합니다.

이거 어떻게 고쳐요?

이 문제를 해결하기 위해 고유한 인코더를 정의할 수 있습니다.

import json
import numpy as np

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

# Your codes .... 
json.dumps(data, cls=NpEncoder)

json에서는 NumPy 데이터 유형을 인식하지 못합니다.숫자를 파이썬으로 변환int개체를 직렬화하기 전에:

'count__c': int(store['count'].iloc[i])

@Jie Yang의 훌륭한 솔루션의 조금 더 안정적인 버전으로 반지에 대한 답변을 드리겠습니다.

나의 해결책

numpyencoder 그리고저장소.

from numpyencoder import NumpyEncoder

numpy_data = np.array([0, 1, 2, 3])

with open(json_file, 'w') as file:
    json.dump(numpy_data, file, indent=4, sort_keys=True,
              separators=(', ', ': '), ensure_ascii=False,
              cls=NumpyEncoder)

고장이

파일에서 hmallen의 코드를 파헤치면 @Jie Yang의 대답과 매우 유사하다는 것을 알 수 있습니다.


class NumpyEncoder(json.JSONEncoder):
    """ Custom encoder for numpy data types """
    def default(self, obj):
        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
                            np.int16, np.int32, np.int64, np.uint8,
                            np.uint16, np.uint32, np.uint64)):

            return int(obj)

        elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):
            return float(obj)

        elif isinstance(obj, (np.complex_, np.complex64, np.complex128)):
            return {'real': obj.real, 'imag': obj.imag}

        elif isinstance(obj, (np.ndarray,)):
            return obj.tolist()

        elif isinstance(obj, (np.bool_)):
            return bool(obj)

        elif isinstance(obj, (np.void)): 
            return None

        return json.JSONEncoder.default(self, obj)

매우 간단한 numpy 인코더는 더 일반적으로 유사한 결과를 얻을 수 있습니다.

참고로 이 기능은 다음을 사용합니다.np.generic클래스(대부분의 np 클래스가 상속하는 클래스) 및 사용a.item()방법.

인코딩할 개체가 numpy 인스턴스가 아닌 경우 json serializer는 정상적으로 계속됩니다.이는 일부 numpy 개체 및 일부 다른 클래스 개체가 있는 사전에 적합합니다.

import json
import numpy as np

def np_encoder(object):
    if isinstance(object, np.generic):
        return object.item()

json.dumps(obj, default=np_encoder)

사실 인코더를 작성할 필요가 없으며 기본값을 다음으로 변경합니다.str전화를 걸 때json.dumps함수는 대부분의 유형을 자체적으로 처리하므로 코드 한 줄로 다음과 같이 처리합니다.

json.dumps(data, default=str)

의 문서에서json.dumps그리고.json.dump: https://docs.python.org/3/library/json.html#json.dump

지정할 경우 기본값은 직렬화할 수 없는 개체에 대해 호출되는 함수여야 합니다.개체의 JSON 인코딩 가능 버전을 반환하거나 TypeError를 발생시켜야 합니다.지정하지 않으면 TypeError가 발생합니다.

소콜링strnumpy 유형(예: numpyints 또는 numpy floats)을 json이 구문 분석할 수 있는 문자열로 변환합니다.하지만 numpy 배열 또는 범위가 있는 경우 먼저 목록으로 변환해야 합니다.이 경우 Jie Yang이 제안한 대로 인코더를 작성하는 것이 더 적합한 해결책이 될 수 있습니다.

numpy 배열을 직렬화하려면 다음을 사용할 수 있습니다.ndarray.tolist()방법.

바보 같은 의사들로부터,

a.tolist() 같습다니의와 거의 .list(a)그것을 제외하고는tolist를 Python 합니다. Python은 numpy scalarsnumpy입니다.

In [1]: a = np.uint32([1, 2])

In [2]: type(list(a)[0])
Out[2]: numpy.uint32

In [3]: type(a.tolist()[0])
Out[3]: int

늦은 답변일 수도 있지만, 최근에 같은 오류가 발생했습니다.많은 서핑을 한 후 이 솔루션이 도움이 되었습니다.

def myconverter(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()
        elif isinstance(obj, datetime.datetime):
            return obj.__str__()

myconverterjson.dumps()아래와 같이 json.dumps('message', default=myconverter)

이 오류가 있는 경우

유형 오류: 'int64' 유형의 개체는 JSON 직렬화할 수 없습니다.

다음과 같이 intd 유형의 특정 열을 float64로 변경할 수 있습니다.

df = df.astype({'col1_int':'float64', 'col2_int':'float64', etc..})

Float64는 Google 스프레드시트에 올바르게 기록됩니다.

을 JSON으로 null.

import json
import numpy as np

class NpJsonEncoder(json.JSONEncoder):
  """Serializes numpy objects as json."""

  def default(self, obj):
    if isinstance(obj, np.integer):
      return int(obj)
    elif isinstance(obj, np.bool_):
      return bool(obj)
    elif isinstance(obj, np.floating):
      if np.isnan(obj):
        return None  # Serialized as JSON null.
      return float(obj)
    elif isinstance(obj, np.ndarray):
      return obj.tolist()
    else:
      return super().default(obj)

# Your code ... 
json.dumps(data, cls=NpEncoder)

이 게시물에는 대부분의 경우에 적합한 훌륭한 답변이 있습니다.하지만 모든 numpy 유형(예: 복잡한 숫자)에 대해 작동하고 json conform(예: 목록 구분 기호로 쉼표)을 반환하는 솔루션이 필요했습니다.

누피 용액

또 다른 옵션은 내부적으로 numpy 배열 또는 값을 문자열 numpy로 변환하는 것입니다. 즉, 다음과 같습니다. np.array2string이 옵션은 매우 강력해야 하며 필요에 따라 출력을 채택할 수 있습니다.

import sys
import numpy as np

def np_encoder(obj):
    if isinstance(obj, (np.generic, np.ndarray)):
        out = np.array2string(obj,
                              separator=',',
                              threshold=sys.maxsize,
                              precision=50,
                              floatmode='maxprec')
        # remove whitespaces and '\n'
        return out.replace(' ','').replace('\n','')

# example usage
data = np.array([0, 1+0j, 3.123, -1, 2, -5, 10], dtype=np.complex128)
json.dumps({'value': data[-1], 'array': data}, default=np_encoder)
# '{"value": "10.+0.j",
#   "array": "[0.+0.j, 1.+0.j, 3.123+0.j, -1.+0.j, 2.+0.j, -5.+0.j, 10.+0.j]"}'

댓글:

  • conform이 를 json list conform으로 .separator=','
  • threshold=sys.maxsize한 항목을 합니다("may summary")....,).
  • 와 함께 (른다파라함께와터미(함()precision,floatmode,formatter할 수
  • json의 과 줄("json", "줄 바꿈")을 모두 했습니다..replace(' ','').replace('\n','')).
update_data = {
    'name': str(store['entity_name'].iloc[i]),
    'count__c': str(store['count'].iloc[i]) 
}

당신이 제수을있경의 할 수 .DataFrame할 수 있습니다: 값표준 Python 유용도예강수있제다습니할록하사형에을예(:▁you다있니:intnumpy.int64을 설정하여 합니다.dtypeobject:

df = pd.DataFrame(data=some_your_data, dtype=object)

분명한 단점은 원시 데이터 유형보다 성능이 떨어진다는 것입니다.하지만 저는 이 솔루션이 마음에 듭니다. 정말 간단하고 가능한 모든 유형의 문제를 제거합니다. 또는 ORM에 를 줄 .json.

저는 쓰레기통에 짐을 싣는 것으로 그것을 작동시킬 수 있었습니다.

코드:

import json

json.loads(json.dumps(your_df.to_dict()))

언급URL : https://stackoverflow.com/questions/50916422/python-typeerror-object-of-type-int64-is-not-json-serializable

반응형