Python - TypeError:“int64”类型的对象不是 JSON 可序列化的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50916422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:38:25  来源:igfitidea点击:

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

pythonnumpy

提问by dark horse

I have a data frame that stores store name and daily sales count. I am trying to insert this to Salesforce using the Python script below. However, I get the following error:

我有一个存储商店名称和每日销售额的数据框。我正在尝试使用下面的 Python 脚本将其插入 Salesforce。但是,我收到以下错误:

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

Below, there is the view of the data frame.

下面是数据框的视图。

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

I use the following code to insert it to Salesforce.

我使用以下代码将其插入 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)

Getting the error, when the last line above gets executed. Could anyone assist in fixing this? Thanks..

得到错误,当上面的最后一行被执行时。任何人都可以协助解决这个问题吗?谢谢..

回答by DYZ

jsondoes not recognize NumPy data types. Convert the number to a Python intbefore serializing the object:

json不识别 NumPy 数据类型。int在序列化对象之前将数字转换为 Python :

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

回答by Jie Yang

You can define your own encoder to solve this problem.

你可以定义自己的编码器来解决这个问题。

import json
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)

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

回答by MattCochrane

Another option is that when you create the dataframe use dtype=str

另一种选择是,当您创建数据框使用 dtype=str

For example, if you loaded storefrom a csv file:

例如,如果您store从 csv 文件加载:

import pandas as pd
store = pd.read_csv('store.csv', dtype=str)

Then everything has a type of strwhich can be serialized to json.

那么一切都有一种str可以序列化为json的类型。

回答by shiva

This might be the late response, but recently i got the same error. After lot of surfing this solution helped me.

这可能是迟到的回应,但最近我遇到了同样的错误。经过大量冲浪后,这个解决方案帮助了我。

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__()

Call myconverterin json.dumps()like below. json.dumps('message', default=myconverter)

通话myconverterjson.dumps()像下面。 json.dumps('message', default=myconverter)

回答by Jason R Stevens CFA

I'll throw in my answer to the ring as a bit more stable version of @Jie Yang's excellent solution.

我将把我的回答作为@Jie Yang优秀解决方案的更稳定版本。

My solution

我的解决方案

numpyencoderand its repository.

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)

The breakdown

故障

If you dig into hmallen'scode in the numpyencoder/numpyencoder.pyfile you'll see that it's very similar to @Jie Yang's answer:

如果您深入研究文件中的hmallen代码,numpyencoder/numpyencoder.py您会发现它与@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)