skip to Main Content

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


  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

    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search