TypeError: Object of type bool_ is not JSON serializable

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: Object of type bool_ is not JSON serializable #

The Python "TypeError: Object of type bool_ is not JSON serializable" occurs when we try to convert a numpy bool_ object to a JSON string. To solve the error, convert the numpy bool_ to a Python bool before converting it to JSON, e.g. bool(my_numpy_bool_).

Here is an example of how the error occurs.

main.py
import json import numpy as np num = np.float64(100) # ⛔️ TypeError: Object of type bool_ is not JSON serializable json_str = json.dumps({'is_subscribed': num > 0})

The num > 0 expression evaluates to a numpy bool_, but the json.dumps() method doesn't handle numpy bool_ objects by default.

To solve the error, use the built-in bool() class to convert the numpy bool_ to a native Python bool before serializing it.

main.py
import json import numpy as np num = np.float64(100) json_str = json.dumps({'is_subscribed': bool(num > 0)}) print(json_str) # 👉️ {"is_subscribed": true} print(type(json_str)) # 👉️ <class 'str'>

The default JSON encoder handles bool values, so we can use a native Python boolean instead of a numpy bool_ when serializing to JSON.

The json.dumps method converts a Python object to a JSON formatted string.

Alternatively, you can extend from the JSONEncoder class and handle the conversions in a default method.

main.py
import json import numpy as np class NpEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.bool_): return bool(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) num = np.float64(100) json_str = json.dumps({'is_subscribed': num > 0}, cls=NpEncoder) print(json_str) # 👉️ {"is_subscribed": true} print(type(json_str)) # 👉️ <class 'str'>

We extended from the JSONEncoder class.

The JSONEncoder class supports the following objects and types by default.

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

The JSONEncoder class doesn't support numpy bool_ to JSON conversion by default.

We can handle this by extending from the class and implementing a default() method that returns a serializable object.

main.py
import json import numpy as np class NpEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.bool_): return bool(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)

If the passed in object is an instance of np.bool_, we convert the object to a Python bool and return the result.

If the passed in object is an instance of np.integer, we convert the object to a Python int and return the result.

If the passed in object is an instance of np.floating, we convert it to a Python float and return the result.

If the object is an instance of np.ndarray, we convert it to a Python list and return the result.

In all other cases, we let the base class's default method do the serialization.

To use a custom JSONEncoder, specify it with the cls keyword argument in your call to the json.dumps() method.

main.py
import json import numpy as np class NpEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.bool_): return bool(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) num = np.float64(100) # ✅ provide the cls keyword argument json_str = json.dumps({'is_subscribed': num > 0}, cls=NpEncoder) print(json_str) # 👉️ {"is_subscribed": true} print(type(json_str)) # 👉️ <class 'str'>

If you don't provide the cls kwarg, the default JSONEncoder is used.

Conclusion #

The Python "TypeError: Object of type bool_ is not JSON serializable" occurs when we try to convert a numpy bool_ object to a JSON string. To solve the error, convert the numpy bool_ to a Python bool before converting it to JSON, e.g. bool(my_numpy_bool_).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.