Harsha
Harsha

Reputation: 363

Convert JSON values datatype from into to string

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)

Upvotes: 0

Views: 1253

Answers (5)

Harsha
Harsha

Reputation: 363

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

Upvotes: 0

pyOliv
pyOliv

Reputation: 1293

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

Upvotes: 1

robinsax
robinsax

Reputation: 1220

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

Upvotes: 1

user2466962
user2466962

Reputation: 1

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

Upvotes: 0

ForceBru
ForceBru

Reputation: 44838

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

Upvotes: 0

Related Questions