0

I am currently writing an api response and the requirement is that all integers must inside double quotes. Ex:

{
"Key1": {"SubKey1":"1", "SubKey2":"2"},
"Key2": "2"
}

When I use json.dumps() to convert my dict to json str I'm getting this result:

{
"Key1": {"SubKey1":1, "SubKey2":2},
"Key2":2
}

(the values of keys are int objects in python). What should I do to make the values appear inside quotes?

I have tried casting them by using

string_ver = {str(key): str(d[key]) for key in d}

but this did not convert the values for subkey into strings (as expected)

4
  • 1
    You should cast them to strings before dumping them to JSON. Commented May 12, 2020 at 20:03
  • Like this new_d = {str(key): str(value) for key, value in keys_values} @robinsax Commented May 12, 2020 at 20:05
  • That will work on your provided sample, yep. Commented May 12, 2020 at 20:08
  • @robinsax I edited my question to be more precise, my proposed solution did not work for this sample case Commented May 12, 2020 at 20:13

5 Answers 5

1

For the record, the reason you're getting answers that don't work is you didn't supply a good piece of sample data. You should make sure your sample input always matches the shape of your true input when posting.

That being said, recursion is your friend here. The following function will return a copy the provided dict with all values cast to string, handling an arbitrary nesting depth. If data contains lists, further modification will be required.

def cast_values_to_str(data):
    result = dict()
    for key, value in data.items():
        if isinstance(value, dict):
            result[key] = cast_values_to_str(value)
        else:
            result[key] = str(value)
    return result
Sign up to request clarification or add additional context in comments.

Comments

1

EDITED: You have to convert recursively each int to strings:

def convert_simple_dct(dct):
    for key, val in dct.items():
        if isinstance(val, dict):
            dct[key] = convert_simple_dct(val)
        else:
            dct[key] = str(val)
    return dct

dct = {
    "Key1": {"SubKey1":1, "SubKey2":2},
    "Key2": 2
}
print(json.dumps(convert_simple_dct(dct)))

2 Comments

I edited my question to be more precise: the python object would be mydict = { "Key1": {"SubKey1":1, "SubKey2":2}, "Key2":2 } Sorry for the confusion
OK, then here you go ;)
0

Integers in your Python dictionary will be represented as integers in the JSON. If you want them to be strings, convert them to strings in Python:

>>> import json
>>> json.dumps({'thing': str(2)})
'{"thing": "2"}'

Comments

0

I cannot reproduce, when I run this code:

In [1]: import json                                                                                                                                                                                                                                                
In [2]: mydict= {"Key1": "1", "Key2": "2"}                                                                                                                                                                                                                         
In [3]: json.dumps(mydict)                                                                                                                                                                                                                                         
Out[3]: '{"Key1": "1", "Key2": "2"}'

1 Comment

I edited my question to be more precise: the python object would be mydict = { "Key1": {"SubKey1":1, "SubKey2":2}, "Key2":2 }
0

Thanx to @pyOliv and @robinsax, I found the solution to it.

def recursive_change_int_to_string(dictObj):
for key, val in dictObj.items():
    if isinstance(val, dict):
        recursive_change_int_to_string(val)
    elif isinstance(val, int):
        dictObj[key] = str(val)

and then

sampleDict = {"Key1": {"SubKey1":1, "SubKey2":2}, "Key2":2 }

recursive_change_int_to_string(sampleDict)

json.dumps(sampleDict )

gave me:

{
"Key1": {"SubKey1":"1", "SubKey2":"2"},
"Key2": "2"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.