在Python中序列化JSON时,“ TypeError :(整数)不可JSON序列化”?

问题:在Python中序列化JSON时,“ TypeError :(整数)不可JSON序列化”?

我正在尝试从python发送一个简单的字典到json文件,但是我一直收到“ TypeError:1425不能序列化JSON”消息。

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

I am trying to send a simple dictionary to a json file from python, but I keep getting the “TypeError: 1425 is not JSON serializable” message.

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

If I add the default argument, then it writes, but the integer values are written to the json file as strings, which is undesirable.

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

回答 0

我发现了问题。问题是我的整数实际上是type numpy.int64

I found my problem. The issue was that my integers were actually type numpy.int64.


回答 1

在python 3中将numpy.int64转储到json字符串中似乎存在问题,并且python团队已经对此进行了讨论。可以在此处找到更多详细信息。

Serhiy Storchaka提供了一种解决方法。它工作得很好,所以我将其粘贴在这里:

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

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

It seems like there may be a issue to dump numpy.int64 into json string in Python 3 and the python team already have a conversation about it. More details can be found here.

There is a workaround provided by Serhiy Storchaka. It works very well so I paste it here:

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

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

回答 2

这为我解决了问题:

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

This solved the problem for me:

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

回答 3

只需将数字从int64(从numpy)转换为int

例如,如果变量x是int64:

int(x)

如果是int64数组:

map(int, x)

Just convert numbers from int64 (from numpy) to int.

For example, if variable x is a int64:

int(x)

If is array of int64:

map(int, x)

回答 4

正如@JAC在评价最高的答案的注释中指出的那样,可以在将numpy dtypes转换为本地python类型的线程中找到通用解决方案(适用于所有numpy类型) 。

不过,我将在下面添加解决方案的版本,因为我需要一个通用的解决方案,该解决方案将这些答案以及其他线程的答案结合在一起。这应该适用于几乎所有的numpy类型。

def convert(o):
    if isinstance(o, np.generic): return o.item()  
    raise TypeError

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

as @JAC pointed out in the comments of the highest rated answer, the generic solution (for all numpy types) can be found in the thread Converting numpy dtypes to native python types.

Nevertheless, I´ll add my version of the solution below, as my in my case I needed a generic solution that combines these answers and with the answers of the other thread. This should work with almost all numpy types.

def convert(o):
    if isinstance(o, np.generic): return o.item()  
    raise TypeError

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

回答 5

这可能是较晚的响应,但最近我遇到了相同的错误。经过大量的冲浪后,此解决方案对我有所帮助。

alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
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(alerts, default=myconverter).

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

alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
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 myconverter in json.dumps() like below. json.dumps(alerts, default=myconverter).


回答 6

或者,您可以先将对象转换为数据框:

df = pd.DataFrame(obj)

然后将其保存dataframejson文件中:

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

希望这可以帮助

Alternatively you can convert your object into a dataframe first:

df = pd.DataFrame(obj)

and then save this dataframe in a json file:

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

Hope this helps


回答 7

您具有Numpy数据类型,只需更改为普通的int()或float()数据类型即可。它将正常工作。

You have Numpy Data Type, Just change to normal int() or float() data type. it will work fine.


回答 8

同样的问题。列出包含numpy.int64类型的数字,该数字引发TypeError。我的快速解决方法是

mylist = eval(str(mylist_of_integers))
json.dumps({'mylist': mylist})

它将列表转换为str(),而eval()函数像python表达式那样评估“字符串”,并在我的情况下以整数列表形式返回结果。

Same problem. List contained numbers of type numpy.int64 which throws a TypeError. Quick workaround for me was to

mylist = eval(str(mylist_of_integers))
json.dumps({'mylist': mylist})

which converts list to str() and eval() function evaluates the String like a Python expression and returns the result as a list of integers in my case.


回答 9

from numpyencoder import NumpyEncoder

在Python3中解决此问题:

import json
from numpyencoder import NumpyEncoder
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',cls=NumpyEncoder))
afile.close()

Use the below code to resolve the issue.

import json
from numpyencoder import NumpyEncoder
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',cls=NumpyEncoder))
afile.close()