2

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

1
  • Got no error on pandas 1.3.5. Commented Dec 21, 2022 at 20:09

2 Answers 2

1

I think this is what you're intending to do:

for key in df.keys():
    df[key] = str(df[key])

Keep in mind this is assigning to df and not data.

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

Sign up to request clarification or add additional context in comments.

Comments

0

You need to loop over the keys of each dict in the list separately.

df = data['cotdata']

for o in df:
    for k, v in o.items():
        o[k] = str(v)

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.