Home > Enterprise >  string indices must be integers when using python with json
string indices must be integers when using python with json

Time:09-30

I want to print the ip addresses from company.json but I am getting the error 'string indices must be integers'

Here is my python code:

import json

f = open('company.json')
data = json.load(f)
f.close()

for item in data["Company"]:
print(item["ip"])

And here is the company.json file:

{
"Company": {
    "Google": {
        "ip": "142.250.115.139",
        "hostname": ""
    },
    "Facebook": {
        "ip": "",
        "hostname": "edge-star-mini-shv-02-iad3.facebook.com"
    },
    "Reddit": {
        "ip": "151.101.193",
        "hostname": ""
    },
    "Spectrum": {
        "ip": "",
        "hostname": ""
    }
}

CodePudding user response:

data["Company"] is a dictionary, so you're iterating over the keys (which are strings). Use data["Company"].values():

import json

with open("company.json", "r") as f_in:
    data = json.load(f_in)

for item in data["Company"].values():
    print(item["ip"])

Prints:

142.250.115.139

151.101.193

CodePudding user response:

data["Company"] returns a dictionary. When iterating over that, you will get string keys for item, since that's what you get by default when iterating over a dictionary. Then you try to do item["ip"], where item is "Google" for example, which causes your error.

You want to iterate the values of the dictionary instead:

for item in data["Company"].values():
    print(item["ip"])
  • Related