0

all,

I encounter an issue with a requirement. I know normally when change python boolean to json format, then gonna use the solution as below:

>>>data = {'key1': True}
>>>data_json = json.dumps(data)
>>>print data_json
{'key1': true}

The issue I have is that I need to have it as {'key1': 'true'}, string with quote ' or double quote ". Anyone knows is there any correct and simple way to do that? Thanks

Zhihong

6
  • 3
    I'm curious about why you'd need booleans to be converted into strings. Are you feeding a very weird API? Commented Sep 25, 2017 at 10:15
  • Is this a pretty predictable dataset where you could simply do {'key1': 'true' if True else 'false'}? Or some potentially deep nested structure with arbitrary values? Commented Sep 25, 2017 at 10:16
  • 1
    well the correct way is without quotes... if you need to add quotes for some reason then you have to process it manually and add it yourself Commented Sep 25, 2017 at 10:17
  • Hi, Felk, yes, that is a API requirement that I send the data to, the example data does need quote. I am still testing whether that is the reason. Actually, The data can be sent without error when I just use original True or False. But the support guy said the value is not correct set. And after change to use true and false, then I got API error. Commented Sep 25, 2017 at 10:37
  • @deceze, it is not complex structure by now. But maybe some nested structure in the future, so I would like a good solution. Commented Sep 25, 2017 at 10:41

2 Answers 2

1

Before calling json.dumps(data), process your data accordingly:

for key in data:
    if type(data[key]) is bool:
        data[key] = str(data[key]).lower()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick answer.
1

If your keys are not nested, then it's just a simple operation of str(value).lower(), otherwise you'd have to do it recursively.

# this should work for basic data types

def convert_booleans(value):
    if isinstance(value, dict):
        return {key: convert_booleans(val) for key, val in value.items()}
    elif isinstance(value, bool):
        return str(value).lower()
    elif hasattr(value, '__iter__'):
        return map(convert_booleans, value)

    return value

converted_data = convert_booleans(data)
print(json.dumps(converted_data))

With that said, it is not an ideal thing to do. JSON object has a special meaning for the boolean value, and it shouldn't be treated as a string. You had better try to convince the client of your api if possible. Most likely, the client is processing the result data as a string and not json, and hence finding it difficult to parse the data.

1 Comment

thanks for the quick answer. Yes, I think then I need process this case separately. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.