Select Page

How to Solve Python TypeError: Object of type bool_ is not JSON serializable

by | Programming, Python, Tips

This error occurs when we try to serialize a numpy.bool_ object to a JSON string using the json.dumps() method. You can solve this error by converting the NumPy bool_ to an ordinary Python bool before passing the object to the json.dumps() method. For example,

import json
import numpy as np

val = np.int32(10**2) > 50

json_str = json.dumps({'X':bool(val)})

This tutorial will detail the error and how to solve it with code examples.


TypeError: Object of type bool_ is not JSON serializable

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type. The part “Object of type bool” tells us the error is due to an illegal operation with an object of the NumPy bool_ class. The numpy.bool_ is a Boolean type (True or False) stored as a byte.

Serialization in Python refers to converting a Python object into a transmittable format that we can recreate when needed using deserialization. JSON serialization returns a human-readable string form called a JSON string. The JSON encoder json.dump() and json.dumps() can only serialize certain object types like dictionaries, lists, or strings.

is not JSON serializable” informs us that the JSON serialization is an illegal operation for the numpy.bool_ type.

Example

Let’s look at an example of serializing a numpy.bool_ object. First, we will import the json and numpy modules and then create a numpy.bool_ object using a comparison operation.

import json
import numpy as np

val = np.int32(10**2) > 50

print(val)

print(type(val))

In the above code, we are evaluating the condition “is 10 squared greater than 50?“, which evaluates to True.

True
<class 'numpy.bool_'>

Next, we will attempt to store the numpy.bool_ object as a value in a dictionary and then serialize the dictionary.

json_str = json.dumps({'X':val})

print(json_str)

Let’s run the code to see what happens:

TypeError: Object of type bool_ is not JSON serializable

The error occurs because val is a numpy.bool_ object, which is not JSON serializable,

Solution #1

The simplest way to solve this error is to convert the numpy.bool_ object to a Python bool object using the built-in bool() method.

Let’s look at the revised code:

import json
import numpy as np

val = np.int32(10**2) > 50

json_str = json.dumps({'X':bool(val)})
print(json_str)

Let’s run the code to get the JSON string containing the Boolean value.

{"X": true}

Solution #2

We can also solve this error by setting the default keyword argument to bool. The function we set as the default keyword argument gets called for objects that are not JSON serializable. This approach is helpful for when we have multiple numpy.bool_ objects we want to serialize.

Let’s look at the revised code:

import json
import numpy as np

val = np.int32(10**2) > 50
val2 = np.int32(4**2) > 50
val3 = np.int32(8**2) > 50

json_str = json.dumps({'X':val, 'Y':val2, 'Z':val3}, default=bool)
print(json_str)

Let’s run the code to see JSON string containing the Boolean values.

{"X": true, "Y": false, "Z": true}

Solution #3

We can also solve this error by building a custom JSONEncoder subclass. This subclass will override the default method to serialize additional types.

import json
import numpy as np

class np_bool_encoder(json.JSONEncoder):

    def default(self, obj):

        if isinstance(obj, np.bool_):

            return bool(obj)

        return json.JSONEncoder.default(self, obj)

Similar to the custom function, the default method of the np_bool_encoder class checks if the object is an instance of numpy.bool_, converts it to a list and returns it.

We have to specify the custom JSONEncoder subclass with the cls keyword argument. Otherwise, JSONEncoder is used. Let’s look at the updated code:

import json
import numpy as np

val = np.int32(10**2) > 50

val2 = np.int32(4**2) > 50

val3 = np.int32(8**2) > 50

json_str = json.dumps({'X':val, 'Y':val2, 'Z':val3}, cls=np_bool_encoder)

print(json_str)

Let’s run the code to see the result:

{"X": true, "Y": false, "Z": true}

Below is the collection of objects that the JSONEncoder class supports by default, and their JSON equivalent.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int- & float- derived Enumsnumber
Truetrue
Falsefalse
Nonenull
JSONEncoder Supported objects and types by default

What is the Difference Between Python bool and numpy bool_?

The numpy.bool_ type is not a subclass of the int_ type and is not a number type. The Python default implementation of bool is a subclass of int.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on “not JSON serializable” TypeErrors, go to the articles:

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!