I am attempting to convert the following dict
into JSON using json.dumps
:
{
\'post_engaged\': 36,
\'post_impressions\':
Modifying the accepted answer above, I wrote a function to handle dictionaries of arbitrary depth:
def stringify_keys(d):
"""Convert a dict's keys to strings if they are not."""
for key in d.keys():
# check inner dict
if isinstance(d[key], dict):
value = stringify_keys(d[key])
else:
value = d[key]
# convert nonstring to string if needed
if not isinstance(key, str):
try:
d[str(key)] = value
except Exception:
try:
d[repr(key)] = value
except Exception:
raise
# delete old key
del d[key]
return d