How to solve TypeError: Object of type int32 is not JSON serializable in Python

The TypeError: Object of type int32 is not JSON serializable is seen when the type of the object we pass cannot be turned into a JSON object. JSON accepts int, float type of objects. However, when you pass the int32 or int64 type of objects (data types supported by numpy) you see an error as these data types are not supported in JSON.

To get rid of this error, convert the object to the int object type.

In this article, let us see what causes this error and also look at ways of fixing this error.

Also check, How to Fix JSONDecodeError: Expecting value: line 1 column 1 (char 0)

What causes TypeError: Object of type int32 is not JSON serializable?

JSON translates the Python’s integer (int) type to a JSON’s number type object. But when objects of numpy types like int32, int64, etc are passed, it doesn’t understand how to translate this in JSON. Hence it throws the TypeError: Object of tye int32 is not JSON serializable.

Lets’s look at an example. Say, we have an array corresponding to some values and we want to write the first value, we see an error.

import json
import numpy as np

values=np.array([50,25,30,28])
first_value=json.dumps({'age':values[0]})
print(first_value)

Output:

Traceback (most recent call last):
File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Test.py", line 12, in <module>
first_value=json.dumps({'age':values[0]})
File "C:\Users\paian\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Users\paian\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\paian\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\paian\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type int32 is not JSON serializable

We see an error in this case as int32 is not supported in JSON. We can solve this by converting it to Pythons’s int object. To do so, we can follow one of the below fixes.

Fix 1: Convert the object to an integer using int()

Use int() type-conversion to convert the required object to Python’s int data type.

import json
import numpy as np

values=np.array([50,25,30,28])
first_value=json.dumps({'age':int(values[0])})
print(first_value)

Output:

{"age": 50}

As seen from the above code, we have converted the 50 from int32 to int type object. Thus we don’t see any error while executing.

Fix 2: Use the ndarray.item() to convert the object to the nearest Python data type

To convert the numpy data type objects to the nearest Python data type object, we can use the ndarray.item() method.

Refer to the below example for more details

import json
import numpy as np

def convert(obj):
# if the data type is on numpy data type object, convert it to nearest Python object using obj.item()
if isinstance(obj,np.generic):
    return obj.item()
else:
raise TypeError

values=np.array([50,25,30,28])
json_object=json.dumps({'age':values[0]},default=convert)
print(first_value)

Output:

{"age": 50}

In the above code, if the data type of the object is not supported in JSON, in this case, int32 object,  the function name specified in the default parameter will be called(in this case, convert). The argument to the function will be an object(int32 object). Within the function, we call ndarray.item() to convert it to the nearest Python data type object( in this case int).

Conclusion:

That brings us to the end of this article. In this article, we have seen what causes the TypeError: Object of type int32 is not JSON serializable with an example. Also, we have seen different ways of fixing this issue. We hope this article has been informative. Kindly comment and let us know the fix that you would implement in your code.

Thanks for reading.

 

 

If you enjoyed reading, share this article.

Anusha Pai is a Software Engineer having a long experience in the IT industry and having a passion to write. She has a keen interest in writing Python Errorfixes, Solutions, and Tutorials.

1 thought on “How to solve TypeError: Object of type int32 is not JSON serializable in Python”

Leave a Comment