I am trying to write a dictionary to a json file with one of the values in boolean format. I get the following error when I am trying to run my code.
raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type bool_ is not JSON serializable
I am currently using Python for this purpose.
It's likely because of this issue (or something similar):
import numpy as np
import json
json.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 json
class 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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With