To fix the TypeError: Object of type ‘int64’ is not JSON Serializable error, “convert the int64 value to a native Python int type before serialization”.
The TypeError: Object of type ‘int64’ is not JSON Serializable error occurs when serializing a Python object containing a NumPy int64 data type to JSON format. The error occurs because the Python json library does not natively support NumPy data types.
Here’s an example that causes the error:
import json
import numpy as np
data = {
"value": np.int64(42)
}
json_data = json.dumps(data)
print(json_data)
Output
TypeError: Object of type int64 is not JSON serializable
To fix this error, you can convert the int64 value to a native Python int type using the int() function.
import json
import numpy as np
data = {
"value": int(np.int64(42))
}
json_data = json.dumps(data)
print(json_data)
Output
{"value": 42}
Alternatively, you can create a custom JSON serializer that handles NumPy int64
values:
import json
import numpy as np
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
return super(NumpyEncoder, self).default(obj)
data = {
"value": int(np.int64(42))
}
json_data = json.dumps(data, cls=NumpyEncoder)
print(json_data)
Output
{"value": 42}
In this example, the NumpyEncoder class extends the json.JSONEncoder class and overrides the default method to handle NumPy int64 values.
When using this custom encoder with the json.dumps() function will serialize the data without raising an error.