Alex.Six
Alex.Six

Reputation: 37

TypeError: string indices must be integers, while reading a json file with python3

I'm trying to read a json file and put its content into a list. When I try to do a for loop to get the contents, I am receiving the error: TypeError: string indices must be integers

Weirdly, if I try to print the file, no problem at all. Does someone know what am I doing wrong? Is the json file ok? 

Here's the json file

{
"Username": "Final test",
"Email": "[email protected]",
"Risks": {
    "Risk1": {
        "Name": "Risco 1",
        "Min": "3000",
        "Likely": "5000"
    },
    "Risk2": {
        "Name": "risco2",
        "Min": "4500",
        "Likely": "6000"
    },
    "Risk3": {
        "Name": "risco3",
        "Min": "1500",
        "Likely": "7000"
    }
  }
}

And here's the python code:

json_file = open('path to file..')
data = json.load(json_file)

lista_json = [data['Username'], data['Email']]
for item in data['Risks']:
    print("item= ", item)
    print("Name, ", data['Risks'][item]['Name'])
    print("Min, ", data['Risks'][item]['Min'])

    lista_json.append(item['Risks'][item]['Name'])
    lista_json.append(item[‘'Risks'][item]['Min'])

Upvotes: 0

Views: 70

Answers (1)

ptrstr
ptrstr

Reputation: 56

You don't seem to be using a proper quote. != '. Also, you're accessing item in the append, not data This is what you want:

json_file = open('path...')
data = json.load(json_file)

lista_json = [data['Username'], data['Email']]
for item in data['Risks']:
    print("item= ", item)
    print("Name, ", data['Risks'][item]['Name'])
    print("Min, ", data['Risks'][item]['Min'])

    lista_json.append(data['Risks'][item]['Name'])
    lista_json.append(data['Risks'][item]['Min'])

Upvotes: 2

Related Questions