[Fixed] TypeError: Object Of Type Float32 Is Not Json Serializable — 2026 Guide

When working with JSON data in Python, you may encounter the TypeError: Object of type float32 is not JSON serializable error.

This error occurs when you try to convert a float32 object into a JSON string, but JSON does not support this data type.

In this article, we’ll explore the various ways to resolve it. We’ll also discuss some best practices to avoid this error in the future.

What is the Typeerror object of type float32 is not json serializable?

The TypeError Object of type float32 is not JSON serializable error occurs when we convert the object float32 into JSON string.

Here is how this error occurs:

import json
import numpy as np

sample = np.power(200, 3.75, dtype=np.float32)

# TypeError: Object of type float32 is not JSON serializable
json_str = json.dumps({'number': sample})

When we run the code this will raise an error:

   raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type float32 is not JSON serializable

The error occurs when we try to pass numply float32 to json.dumps() method wherein this method by default does not handle numpy floats.

Now let’s find out how to fix this error…

How to fix Typeerror object of type float32 is not json serializable

Here are the following solution you can try to fix the error Typeerror object of type float32 is not json serializable.

1. Using the built-in float or str constructor

The first way to solve the error is by using the built-in float() or str() constructors.

We use this before serializing it wherein it converts the numPy float into a native python float.

Here is the example code:

import json
import numpy as np

sample = np.power(200, 3.75, dtype=np.float32)

print(sample)

# convert to float
json_str = json.dumps({'sample': float(sample)})

print(json_str)
print(type(json_str))

Expected Output:

425463680.0
{"sample": 425463680.0}
<class 'str'>

As we can see we use the float() constructor in converting the numpy float32 into native python.

Meanwhile use str() constructor in converting the value to string concerning loss of precision.

To handle float and str values we are using a JSON encoder.

Hence we can now use the native python float when serializing JSON instead of float32.

2. Create a custom class

Another way is creating a custom class, using JSONEncoder.

This will handle the conversion by default.

Here are the JSONEncoder classes which support the following objects and types.

PythonJSON
list, tuplearray
dictobject
int, float, int and float-derived Enumsnumber
strstring
Nonenull
Falsefalse
Truetrue

As we can observe Numpy float32 is not supported by the JSONEncoder in converting to JSON by default.

To fix this we will implement default() method and extend from the class which returns a serializable object.

Here is the example code:

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)


sample = np.power(200, 3.75, dtype=np.float32)

json_str = json.dumps({'sample': sample}, cls=NpEncoder)

print(json_str)
print(type(json_str))

Expected Output:

{"sample": 425463680.0}
<class 'str'>

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

Meanwhile, we convert to python float and return the result if the passed-in object is an instance of np.floating.

Best practices to avoid the error

To avoid the Object of type float32 is not JSON serializable type error in your Python code, consider the following best practices:

  • Use appropriate data types
    • When working with JSON data, ensure that you use data types that are supported by JSON, such as int, float, str, bool, list, and dict.
  • Convert float32 objects
    • For example, you can convert float32 to float or int using the float() or int() functions, respectively.
  • Use a JSON encoder
    • Instead of manually converting your Python objects to JSON strings, consider using a JSON encoder, such as the json module’s JSONEncoder.
  • Customize JSON encoding
    • If you need to serialize custom data types, you can define a custom encoder that inherits from JSONEncoder.
    • Thus overrides the default() method to handle the serialization of your custom objects.

Conclusion

In conclusion, the TypeError Object of type float32 is not JSON serializable error occurs when we convert the object float32 into JSON string.

Luckily, we can fix it using the built-in float or str constructor and create a custom class using JSONEncoder.

We hope you have learned about this topic and configured your error at the same time.

If you are finding solutions to some errors you might encounter we also have Unhandled rejection typeerror failed to fetch

Thank you for reading!

Understanding int/str/float TypeErrors

Python separates numeric types from strings strictly. Concatenating, comparing, and arithmetic across type boundaries requires explicit conversion.

Common triggers

  • User input is always str. input() always returns str. Wrap with int() or float().
  • CSV cells are all str. Even numeric-looking columns are strings until converted.
  • JSON numbers vs str. json.loads preserves the JSON type — but only “123” as string in the JSON becomes str in Python.
  • Format string mismatch. "%d" % "5" raises TypeError. Use int("5") first.
  • Compare int and str. Python 3 fails on "1" < 2. Convert one side first.

Diagnostic pattern

# BAD — user input treated as int
age = input("Enter your age: ")
if age >= 18:  # TypeError: '>=' not supported between 'str' and 'int'
    print("Adult")

# GOOD — convert first, guard failure
try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Invalid age")
    age = 0

if age >= 18:
    print("Adult")

Best practices

  • Convert at boundaries. Convert input, config values, and API responses to the right type immediately after loading.
  • Use pydantic or dataclasses. Modern data validation libraries convert and check types automatically.
  • Avoid == across types. Compare like-to-like.

Frequently Asked Questions

What is Python TypeError and what causes it?

TypeError is raised when an operation is applied to an object of the wrong type. Common patterns: calling a non-callable object, adding incompatible types (str + int), passing the wrong number of arguments, or accessing attributes on a NoneType. Each TypeError message names the operation and expected vs actual types, the fix is almost always to convert types explicitly (int(), str()) or fix the wrong variable assignment.

How do I quickly debug a Python TypeError?

Three steps: (1) Read the full error message, it names the exact operation and types involved. (2) Print the type of every variable in that line: print(type(var1), type(var2)). (3) Check what the function expected vs what you passed. Most TypeError fixes are 1-line type casts or fixing a variable that became None unexpectedly.

Should I catch TypeError or let it propagate?

For internal code, let TypeError propagate, it’s almost always a real bug (wrong type passed). For boundary code (parsing user input, third-party API responses), catch TypeError + ValueError together: try: parsed = int(value) except (TypeError, ValueError): parsed = 0. Catching internal TypeErrors hides bugs.

How do I prevent TypeError in production?

Three patterns: (1) Use type hints (def add(a: int, b: int) -> int) and check with mypy / pyright in CI. (2) Validate inputs at boundaries (Pydantic for FastAPI, DRF serializers for Django). (3) Default values that match expected types (return 0 not None for numeric functions). Static typing catches 80% of TypeErrors before runtime.

Where can I find more TypeError fixes?

Browse the TypeError reference hub for 220+ specific TypeError fixes. For broader Python debugging, see the Python Tutorial hub. For related error types, see ValueError and AttributeError guides.

Glay Eliver


Programmer & Technical Writer at PIES IT Solution

Glay Eliver is a programmer and writer at PIES IT Solution, author of over 600 tutorials at itsourcecode.com. Specializes in JavaScript tutorials, Microsoft Office how-tos (Excel, Word, PowerPoint), and Python error debugging covering ImportError, TypeError, AttributeError, ModuleNotFoundError, and JavaScript ReferenceError. Authored several of the site’s highest-traffic Excel and MS Office reference articles.

Expertise: JavaScript · MS Excel · MS Word · MS PowerPoint · Python · Python ImportError · Python TypeError · Python AttributeError · ModuleNotFoundError · JavaScript ReferenceError · Pygame
 · View all posts by Glay Eliver →