I have a JSON file That provides the values as integers, so I need to change them to strings to continue with my project.
Here’s the JSON (there’s more pairs but this is for examples sake):
{
"cotdata": [
{
"AUDLONGDEALERINTERMEDIARY": 22990,
"GBPLONGASSETMANAGERS": 39765
}
]
}
My code attempts to convert the values from integers to strings:
import json
with open("myjson.json", "r") as f:
data = json.load(f)
df = data['cotdata']
for key in df:
for value in key:
key[value] = str(key[value])
Although the error I get is: TypeError: string indices must be integers
Is there a way for me to correct this code? Or should I try a different logic
2
Answers
I think this is what you’re intending to do:
Keep in mind this is assigning to
df
and notdata
.I think casting the int to a string wherever it is being used would be much more efficient than this, but it’s hard to say since I don’t know your use-case
You need to loop over the keys of each dict in the list separately.