How to Resolve "TypeError: Object of type numpy.int64/float32 is not JSON serializable" in Python
When working with NumPy arrays, you might encounter TypeError: Object of type int64 is not JSON serializable or TypeError: Object of type float32 is not JSON serializable. These errors occur because Python's standard json module doesn't natively recognize NumPy's specific numeric types.
This guide explains why this happens and provides several practical solutions for successful JSON serialization.
Understanding the Error: JSON and NumPy Types
JSON (JavaScript Object Notation) is a text-based format with a limited set of data types (strings, numbers, booleans, arrays, objects, null). Python's json.dumps() function can serialize standard Python types like int, float, str, list, dict, bool, and None.
However, NumPy introduces its own, more specialized numeric types (like numpy.int64, numpy.float32) to handle large datasets and optimize performance. These NumPy-specific types are not directly recognized by the default JSON encoder.
import json
import numpy as np
# Example causing int64 TypeError
salary_int = np.int64(100000000)
# json_str = json.dumps({'salary': salary_int}) # ⛔️ TypeError
# Example causing float32 TypeError
salary_float = np.float32(316227.78)
# json_str = json.dumps({'salary': salary_float}) # ⛔️ TypeError
Solution 1: Convert NumPy Types to Python Primitives (Recommended)
The simplest and often most effective solution is to explicitly convert the NumPy numeric types to their standard Python equivalents (int or float) before serialization:
Converting NumPy Integers (np.int64, np.int32, etc.)
Use the built-in int() constructor:
import json
import numpy as np
salary_int = np.int64(100000000)
# Convert NumPy int to Python int
json_str = json.dumps({'salary': int(salary_int)})
print(json_str) # Output: {"salary": 100000000}
print(type(json_str)) # Output: <class 'str'>