简体   繁体   中英

Convert bool values to string in json.dumps()

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.)

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"}

You can use the following one-liner:

{k:str(v).lower() for k,v in d.items()}

Output:

{'a': 'false', 'b': 'true'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM