TypeError: Object of type bool_ is not JSON serializable
It's likely because of this issue (or something similar):
import numpy as npimport jsonjson.dumps({"X": np.int32(5) > 5})
TypeError: Object of type 'bool_' is not JSON serializable
The issue is that you end up with something of type bool_
instead of bool
.
Calling bool()
on whichever value(s) are of the wrong type will fix your issue (assuming your version of bool_
behaves similarly to numpy's:
json.dumps({"X": bool(np.int32(5) > 5)})
'{"X": false}'
If you have multiple bool_
keys or a nested structure, this will convert all bool_
fields including deeply nested values, if any:
import jsonclass CustomJSONizer(json.JSONEncoder): def default(self, obj): return super().encode(bool(obj)) \ if isinstance(obj, np.bool_) \ else super().default(obj)
Then to convert the object/dict:
json.dumps(d, cls=CustomJSONizer)
Convert the bool value to a string - dict["your_key"] = str(bool value)