Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Object of type bool_ is not JSON serializable

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.

like image 475
Zainab Saeed Avatar asked Oct 16 '19 07:10

Zainab Saeed


2 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}'

like image 192
Eric Le Fort Avatar answered Oct 28 '22 16:10

Eric Le Fort


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)
like image 11
Justas Avatar answered Oct 28 '22 17:10

Justas