Convert bool values to string in json.dumps()
If it were me, I'd convert the Python data structure to the required format and then call json.dumps()
:
import json
import sys
def convert(obj):
if isinstance(obj, bool):
return str(obj).lower()
if isinstance(obj, (list, tuple)):
return [convert(item) for item in obj]
if isinstance(obj, dict):
return {convert(key):convert(value) for key, value in obj.items()}
return obj
dct = {
"is_open": True
}
print (json.dumps(dct))
print (json.dumps(convert(dct)))
Output:
{"is_open": true}
{"is_open": "true"}
Du D.
I'm a software developer by trade, currently I fell in loved with django and still searching for latest and greatest toys.
Updated on June 09, 2022Comments
-
Du D. almost 2 years
I'm trying to convert a python dict into json, however the API I'm accessing doesn't take bool value instead it uses "true"/"false" string.
Example:
dct = { "is_open": True } json.dumps(dct)
currently gives a bool output:
{ "is_open": true }
but what I want is lower-case string output:
{ "is_open": "true" }
I tried
json.dumps(dct, cls=MyEncoder)
but it doesn't work, only non-native object get passed to MyEncoder default.class MyEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, bool): return str(o).lower() return super(MyEncoder, self).default(o)
Any help would be great.
(Btw this is not my API I'm accessing, so I can't modify the API to access true false value instead of the string alternative.)
-
matth about 7 yearsSo that the Python expression
{True: "yellow"}
becomes the JSON document{"true": "yellow"}
. Your question doesn't limit the conversion requirement to just dictionary values.