TypeError: Object of type bool_ is not JSON serializable

Viewed 13963

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.

4 Answers

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)

I solved this by converting the list from _bool type to bool type like this:

bool_list = np.array(bool_list, dtype=bool).tolist()

now calling:

json.dumps(bool_list)

should work

Convert the bool value to a string - dict["your_key"] = str(bool value)

Related