TypeError:int64 类型的对象不是 JSON 可序列化的

目录

TypeError: Object of type int64 is not JSON serializable

  1. TypeError:int64 类型的对象不是 JSON 可序列化的
  2. 类型错误:float32 类型的对象不是 JSON 可序列化的

TypeError: 类型为 int64 的对象不是 JSON 可序列化的

当我们尝试将 NumPy int64 对象转换为 JSON 字符串时,会出现 Python“TypeError: Object of type int64 is not JSON serializable”。

要解决该错误,请先将 NumPy int 转换为 Python 整数,然后再将其转换为 JSON,例如int(my_numpy_int).

下面是错误如何发生的示例。

主程序
import json import numpy as np salary = np.power(100, 4, dtype=np.int64) # ⛔️ TypeError: Object of type int64 is not JSON serializable json_str = json.dumps({'salary': salary}) print(json_str)

我们尝试将numpy int64 对象传递给该json.dumps()方法,但默认情况下该方法不处理numpy整数。

使用内置intfloat类来解决错误

要解决该错误,请在序列化之前使用内置的
int()(或)构造函数将 numpy 整数转换为本机 Python 整数。float

主程序
import json import numpy as np salary = np.power(100, 4, dtype=np.int64) # 👇️ convert to int json_str = json.dumps({'salary': int(salary)}) print(json_str) # 👉️ '{"salary": 100000000}' print(type(json_str)) # 👉️ <class 'str'>

默认的 JSON 编码器句柄int和值,因此我们可以在序列化为 JSON 时float使用本机 Pythonint而不是int。numpy

json.dumps方法将 Python 对象转换为 JSON 格式字符串。

扩展JSONEncoder类解决错误

或者,您可以从JSONEncoder类扩展并在方法中处理转换default

主程序
import json import numpy as np salary = np.power(100, 4, dtype=np.int64) 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 json.JSONEncoder.default(self, obj) json_str = json.dumps({'salary': salary}, cls=NpEncoder) print(json_str) # 👉️ '{"salary": 100000000}' print(type(json_str)) # 👉️ <class 'str'>

我们从
JSONEncoder
类扩展而来。

该类JSONEncoder默认支持以下对象和类型。

Python JSON
字典 目的
列表,元组 大批
海峡 细绳
int、float、int 和 float 派生枚举 数字
真的 真的
错误的 错误的
没有任何 无效的

请注意,该类默认JSONEncoder不支持int64 到 JSON 的转换。numpy

我们可以通过从类扩展并实现一个default()
返回可序列化对象的方法来处理这个问题。

主程序
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 json.JSONEncoder.default(self, obj)

如果传入的对象是 的实例np.integer,我们将对象转换为 Pythonint并返回结果。

如果传入的对象是 的实例np.floating,我们将其转换为 Pythonfloat并返回结果。

如果对象是 的实例np.ndarray,我们将其转换为 Pythonlist
并返回结果。

In all other cases, we let the base class’s default method do the serialization.

To use a custom JSONEncoder, specify it with the cls keyword argument in
your call to the json.dumps() method.

main.py
import json import numpy as np salary = np.power(100, 4, dtype=np.int64) 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 json.JSONEncoder.default(self, obj) # ✅ pass cls kwarg json_str = json.dumps({'salary': salary}, cls=NpEncoder) print(json_str) # 👉️ '{"salary": 100000000}' print(type(json_str)) # 👉️ <class 'str'>

If you don’t provide the cls kwarg, the default JSONEncoder is used.

# Using the default keyword argument to solve the error

You can also use the default keyword argument in the call to the
json.dumps() method.

main.py
import json import numpy as np salary = np.power(100, 4, dtype=np.int64) json_str = json.dumps({'salary': salary}, default=int) print(json_str) # 👉️ '{"salary": 100000000}' print(type(json_str)) # 👉️ <class 'str'>

The json.dumps method converts a Python
object to a JSON formatted string.

The default keyword argument can be set to a function that gets called for objects that can’t otherwise be serialized.

We simply convert the numpy.int64 object to an integer by passing it to the
int class.

You can also define a custom JSON serializer function.

main.py
import json import numpy as np salary = np.power(100, 4, dtype=np.int64) def json_serializer(obj): if isinstance(obj, np.int64): return int(obj) return obj json_str = json.dumps({'salary': salary}, default=json_serializer) print(json_str) # 👉️ '{"salary": 100000000}' print(type(json_str)) # 👉️ <class 'str'>

We set the default keyword argument to the custom json_serializer function.

The function uses the isinstance() function to check if the value is of type
numpy.int64.

If the value is of type numpy.int64, we convert it to an integer and return
the result.

Otherwise, the value is returned as is.

# TypeError: Object of type float32 is not JSON serializable

The Python “TypeError: Object of type float32 is not JSON serializable” occurs
when we try to convert a numpy float32 object to a JSON string.

To solve the error, convert the numpy float to a Python float before
converting it to JSON, e.g. float(my_numpy_float).

Here is an example of how the error occurs.

main.py
import json import numpy as np salary = np.power(100, 2.75, dtype=np.float32) # ⛔️ TypeError: Object of type float32 is not JSON serializable json_str = json.dumps({'salary': salary})

We tried passing a numpy float32 object to the json.dumps() method but the
method doesn’t handle numpy floats by default.

# Use the built-in float or str constructor to convert the numpy float

To solve the error, use the built-in float() (or
str()) constructor to convert the numpy
float to a native Python float before serializing it.

main.py
import json import numpy as np salary = np.power(100, 2.75, dtype=np.float32) print(salary) # 👉️ 316227.78 # ✅ convert to float json_str = json.dumps({'salary': float(salary)}) print(json_str) # 👉️ '{"salary": 316227.78125}' print(type(json_str)) # 👉️ <class 'str'>

We used the built-in float() constructor to convert the NumPy float32 value to
a native Python float.

Note that if you are worried about losing precision, you can use the str() constructor to convert the value to a string instead.

The default JSON encoder handles float and str values, so we can use a
native Python float instead of a NumPy float32 when serializing to JSON.

The json.dumps method converts a Python
object to a JSON formatted string.

# Create a custom class to handle the conversion

Alternatively, you can extend from the JSONEncoder class and handle the
conversions in a default method.

main.py
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): # 👇️ alternatively use str() return float(obj) if isinstance(obj, np.ndarray): return obj.tolist() return json.JSONEncoder.default(self, obj) salary = np.power(100, 2.75, dtype=np.float32) json_str = json.dumps({'salary': salary}, cls=NpEncoder) print(json_str) # 👉️ {"salary": 316227} print(type(json_str)) # 👉️ <class 'str'>

We extended from the
JSONEncoder
class.

The JSONEncoder class supports the following objects and types by default.

Python JSON
dict object
list, tuple array
str string
int, float, int and float derived Enums number
True true
False false
None null

Notice that the JSONEncoder class doesn’t support NumPy float32 to JSON
conversion by default.

We can handle this by extending from the class and implementing a default()
method that returns a serializable object.

main.py
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 json.JSONEncoder.default(self, obj)

If the passed-in object is an instance of np.integer, we convert the object to
a Python int and return the result.

If the passed-in object is an instance of np.floating, we convert it to a
Python float and return the result.

Note that you can use the str() constructor instead of float() if you worry about losing precision.

If the object is an instance of np.ndarray, we convert it to a Python list
and return the result.

In all other cases, we let the base class’s default method do the serialization.

To use a custom JSONEncoder, specify it with the cls keyword argument in
your call to the json.dumps() method.

main.py
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 json.JSONEncoder.default(self, obj) salary = np.power(100, 2.75, dtype=np.float32) # ✅ pass cls kwarg json_str = json.dumps({'salary': salary}, cls=NpEncoder) print(json_str) # 👉️ {"salary": 316227} print(type(json_str)) # 👉️ <class 'str'>

如果您不提供clskwarg,JSONEncoder则使用默认值。