Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 774
Du D. Avatar asked Mar 07 '17 21:03

Du D.


People also ask

Does JSON dumps convert to string?

dumps() is for converting to JSON, not from JSON to string. str has absolutely nothing to do with JSON; the fact that str(somedict) looks sort of like JSON is coincidence.

What is JSON dumps () method?

The dump() method is used when the Python objects have to be stored in a file. The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc, . The dump() needs the json file name in which the output has to be stored as an argument.

What's the difference between JSON dump and JSON dumps?

json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.

What type is JSON dumps?

dumps() in Python. The full-form of JSON is JavaScript Object Notation.


1 Answers

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"}
like image 179
Robᵩ Avatar answered Oct 23 '22 14:10

Robᵩ