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.
Python | JSON |
---|---|
list, tuple | array |
dict | object |
int, float, int and float-derived Enums | number |
str | string |
None | null |
False | false |
True | true |
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!