I want to convert a dictionary to a JSON string with boolean True
values translated to the number 1
and boolean False
values translated to the number 0
. I'm using a JSONEncoder
subclass, but it seems to ignore booleans ...
import json
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, bool):
return 1 if obj else 0
return super().default(obj)
data = { 'key-a' : 'a', 'key-true' : True, 'key-false' : False }
jsondata = json.dumps(data, cls=MyEncoder)
print(jsondata)
I want this to be the result:
{"key-true": 1, "key-a": "a", "key-false": 0}
However, this is what I get:
{"key-true": true, "key-a": "a", "key-false": false}
I know I can programatically modify the data before passing it to json.dumps
, but is there any way I can obtain my desired result via a JSONEncoder
subclass?