Reputation: 39
I want to print the ip addresses from jobs.json but I am getting the error 'string indices must be integers'
Here is my python code:
import json
f = open('jobs.json')
data = json.load(f)
f.close()
for item in data["Jobs"]:
print(item["ip"])
And here is the Jobs.json file:
{
"Jobs": {
"Carpenter": {
"ip": "123.1432.515",
"address": ""
},
"Electrician": {
"ip": "643.452.234",
"address": "mini-iad.com"
},
"Plumber": {
"ip": "151.101.193",
"Address": "15501 Birch St"
},
"Mechanic": {
"ip": "218.193.942",
"Address": "Yellow Brick Road"
}
}
Upvotes: 1
Views: 180
Reputation: 45742
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"])
Upvotes: 0
Reputation: 195428
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
Upvotes: 1