Encountering a TypeError: Object of type int64 is not JSON serializable is a rite of passage for almost every Python developer working with data science libraries like Pandas and NumPy. And this error halts your workflow exactly when you try to convert a Python object—often a dictionary, list, or Pandas DataFrame—into a JSON string using the standard library's json. dumps() method. Understanding why this happens and how to fix it efficiently is essential for building solid data pipelines and APIs.
Understanding the Root Cause
The Python standard json module is designed to serialize a specific set of native Python types: dict, list, tuple, str, int, float, bool, and None. It does not natively understand specialized numerical types provided by third-party libraries Simple as that..
When you use NumPy or Pandas, numerical data is often stored in optimized C-based data structures like numpy.int64, numpy.float64, numpy.bool_, or numpy.ndarray. While these objects behave like their Python counterparts in mathematical operations, they are distinct classes. When the json encoder encounters a numpy.int64, it lacks the logic to convert it into a valid JSON number, resulting in the familiar TypeError.
This issue appears most frequently in scenarios such as:
- Converting a Pandas DataFrame row (a Series) to a dictionary and then to JSON. So * Returning NumPy scalar values from a Flask or FastAPI endpoint without a custom encoder. * Saving machine learning model parameters or metrics that contain NumPy types.
Solution 1: Custom JSON Encoder (The reliable Approach)
The most architecturally sound solution for applications—especially APIs—is to subclass json.Which means jSONEncoder. By overriding the default() method, you teach the serializer how to handle NumPy types globally. This keeps your business logic clean and separates serialization concerns.
import json
import numpy as np
class NumpyEncoder(json.Which means jSONEncoder):
"""Custom encoder for numpy data types. """
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.And floating):
return float(obj)
if isinstance(obj, np. ndarray):
return obj.On top of that, tolist()
if isinstance(obj, np. bool_):
return bool(obj)
# Let the base class default method raise the TypeError
return super().
# Usage
data = {"user_id": np.int64(42), "score": np.float64(99.5), "active": np.bool_(True)}
json_string = json.dumps(data, cls=NumpyEncoder)
print(json_string)
# Output: {"user_id": 42, "score": 99.5, "active": true}
Why this works: The default method is only called for objects the standard encoder doesn't recognize. By checking isinstance against np.integer (the abstract base class for int8, int16, int32, int64, etc.), you catch all integer variants in one go. Returning obj.tolist() for arrays recursively converts nested structures into native Python lists Practical, not theoretical..
Solution 2: Pandas Built-in Serialization (The "Data Science" Way)
If your primary data structure is a Pandas DataFrame or Series, you rarely need to manually call json.dumps(). Pandas provides highly optimized, built-in methods that handle type conversion internally Turns out it matters..
to_json() Method
This is the single most efficient way to serialize a DataFrame.
import pandas as pd
import numpy as np
df = pd.array([1, 2, 3], dtype='int64'),
'value': np.Still, dataFrame({
'id': np. 5, 20.array([10.3, 30.
# Orient='records' creates a list of dictionaries [{col: val}, ...]
json_output = df.to_json(orient='records')
print(json_output)
# Output: [{"id":1,"value":10.5},{"id":2,"value":20.3},{"id":3,"value":30.1}]
Key orient parameters:
records: List of objects (best for APIs).split: Separate columns, index, and data (preserves dtypes perfectly).index: Dictionary of index -> values.table: JSON Table Schema (includes metadata for round-tripping).
to_dict() Method
If you need a Python dictionary first (e.g., to merge with other data before dumping), use to_dict(orient='records'). This automatically converts int64 to Python int Less friction, more output..
# Returns native Python types
native_dict = df.to_dict(orient='records')
# [{'id': 1, 'value': 10.5}, ...]
json_string = json.dumps(native_dict) # Works natively now
Solution 3: Pre-processing with tolist() or item()
For ad-hoc scripts or single values where importing a custom encoder feels like overkill, you can manually convert the problematic scalar before serialization.
For NumPy Scalars (0-d arrays)
Use the .item() method. It returns a standard Python scalar And that's really what it comes down to..
import numpy as np
import json
val = np.int64(100)
# json.dumps(val) -> TypeError
json.dumps(val.
### For NumPy Arrays (1-d or higher)
Use `.tolist()` to recursively convert the array into a nested Python list.
```python
arr = np.array([[1, 2], [3, 4]], dtype='int64')
json.dumps(arr.tolist()) # Works: "[[1, 2], [3, 4]]"
For Pandas Series
A Series is essentially a 1-d array with an index. Use .tolist() on the values or .to_dict() That alone is useful..
s = pd.Series([1, 2, 3], dtype='int64')
json.dumps(s.tolist()) # "[1, 2, 3]"
json.dumps(s.to_dict()) # "{"0": 1, "1": 2, "2": 3}"
Solution 4: Framework-Specific Integrations (FastAPI, Flask, Django)
Modern Python web frameworks anticipate this issue and offer native solutions.
FastAPI / Pydantic (Automatic Handling)
FastAPI uses Pydantic for data validation and serialization. Pydantic v2 handles NumPy types automatically if you install the optional dependencies or define models correctly.
from fastapi import FastAPI
from pydantic import BaseModel
import numpy as np
app = FastAPI()
class Item(BaseModel):
# Pydantic v2 coerces numpy types automatically
id: int
score: float
@app.post("/items/")
async def create_item(item: Item):
# You can pass numpy types here; Pydantic validates & serializes
return item
# Even returning a dict with numpy types works in recent versions:
@app.get("/legacy")
async def legacy():
return {"id": np.int64(1), "score": np.float64(0.9)}
Flask (Custom JSON Provider)
Flask 2.3+ uses a JSONProvider class. You can customize it globally.
from flask import Flask, jsonify
from flask.json.provider import DefaultJSONProvider
import numpy as np
class NumpyJSONProvider(DefaultJSONProvider):
def dumps(self, obj, **kwargs):
# Reuse the custom encoder logic
return json.dumps
```python
from flask import Flask, jsonify
from flask.json.provider import DefaultJSONProvider
import numpy as np
class NumpyJSONProvider(DefaultJSONProvider):
def dumps(self, obj, **kwargs):
# Reuse the custom encoder logic
return json.dumps(obj, cls=NumpyEncoder, **kwargs)
app = Flask(__name__)
app.json = NumpyJSONProvider(app) # Register the provider globally
@app.route("/data")
def data():
return jsonify({"id": np.int64(1), "values": np.
### Django (Django REST Framework)
Django REST Framework (DRF) relies on its own `JSONRenderer`. The cleanest approach is to override the renderer with your custom encoder, or rely on serializers that coerce types into native Python before rendering.
```python
from rest_framework.renderers import JSONRenderer
from core.custom_encoder import NumpyEncoder
class NumpyJSONRenderer(JSONRenderer):
encoder_class = NumpyEncoder
# In settings.py
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'myapp.renderers.NumpyJSONRenderer',
),
}
The pattern is consistent across frameworks: locate the single serialization entry point and inject your encoder there. Once done, every endpoint benefits without per-route boilerplate.
Choosing the Right Approach
The four solutions map to different trade-offs. A quick decision guide:
- Custom
JSONEncoder(Solution 1) — Best default for most applications. Centralized, reusable, and works anywherejson.dumpsis called. Subclassdefault()and call.item()on unknown types. to_dict(orient='records')(Solution 2) — Ideal when your entire payload is a DataFrame. It converts the whole structure at once and produces clean, native Python types with minimal code..tolist()/.item()(Solution 3) — Best for ad-hoc scripts, notebooks, or single values. No imports, no classes, just an inline conversion at the point of use.- Framework integrations (Solution 4) — The right choice when you control the framework's serialization layer. Configure once and forget about it.
As a rule of thumb: reach for the custom encoder in library or service code, use to_dict when a DataFrame is the natural boundary of your data, and reserve manual .item()/.tolist() for quick one-offs.
A Note on Precision and Edge Cases
A few subtleties are worth keeping in mind as your data grows:
- Float precision.
np.float64maps cleanly to Pythonfloat, butnp.float32loses precision when widened. If exact values matter, convert explicitly and be aware of the representation you are serializing. - NaN and Infinity. NumPy and Pandas happily produce
np.nan,np.inf, and-np.inf. Standard JSON has no representation for these. Python'sjsonmodule emitsNaN,Infinity, and-Infinityby default, which is invalid JSON that strict parsers (and many browsers) will reject. Sanitize these values before serialization, for example withdf.replace([np.inf, -np.inf], None)ordf.where(pd.notnull(df), None). - Timestamps and
Timedelta.pd.Timestampandpd.Timedeltaare not JSON serializable either. Convert with.isoformat()or.total_seconds()respectively, and add them to your encoder'sdefault()alongside the NumPy types. - Complex numbers.
np.complex128has no JSON equivalent. Decide on a convention (e.g., a{"real": ..., "imag": ...}object) and handle it explicitly in your encoder.
Conclusion
The "Object of type int64 is not JSON serializable" error is not a bug in your code — it is the expected result of handing a JSON encoder objects it was never designed to understand. NumPy and Pandas introduce their own scalar and array types for performance and memory efficiency, and the standard json module simply does not know how to reduce them to native Python primitives.
The fix is always the same in spirit: convert NumPy and Pandas types into native Python int, float, str, list, and dict before they reach the encoder. item()and.But whether you do that with a reusable JSONEncoder subclass, a bulk to_dict(orient='records') call, inline . tolist() conversions, or a framework-level integration, the goal is identical — bridge the gap between the numerical computing stack and the JSON data format.
Not obvious, but once you see it — you'll see it everywhere.
Start with the custom encoder as your general-purpose tool, layer in to_dict when DataFrames define your data boundaries, and configure your framework once so the problem never resurfaces. Handle the edge cases — NaN, infinity, timestamps, and precision — deliberately rather
than letting them break your serialization at the worst possible moment. By treating these conversions as a first-class part of your data pipeline, you check that your applications remain solid, predictable, and ready to exchange data with the broader JSON ecosystem It's one of those things that adds up..