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.)
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.
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.
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.
dumps() in Python. The full-form of JSON is JavaScript Object Notation.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With