Reputation: 441
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.
Upvotes: 34
Views: 28499
Reputation: 9658
You can set a default for json:
print (json.dumps(mydict, indent=2, default=str))
Upvotes: 1
Reputation: 1
If you have a pandas dataframe and writing its values into a json file, you can do this:
bool(df['col_name_with_bool_values'].iat[0])
Upvotes: 0
Reputation: 2691
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}'
Upvotes: 45
Reputation: 1
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
Upvotes: 0
Reputation: 5942
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)
Upvotes: 21
Reputation: 5
Convert the bool value to a string - dict["your_key"] = str(bool value)
Upvotes: -2