How to loop through json data with multiple objects

My json file looks like this

[
{"host" : "192.168.0.25", "username":"server2", "path":"/home/server/.ssh/01_id"},
{"host" : "192.168.0.26", "username":"server3", "path":"/home/server/.ssh/01_id"}

]

I want the loop happen in this way only (lets ignore the remote variable)

for remotes,host,username in zip(remote , data["host"] ,data["username"]):

This is the error i am getting

    for remotes,host,username in list(zip(remote , data["host"] ,data["username"])):
TypeError: list indices must be integers or slices, not str

>Solution :

You need to iterate the data to extract the host and username values so that you can zip them to the remote list:

data = [
 {"host" : "192.168.0.25", "username":"server2", "path":"/home/server/.ssh/01_id"},
 {"host" : "192.168.0.26", "username":"server3", "path":"/home/server/.ssh/01_id"}
]
hosts_users = [(d['host'], d['username']) for d in data]
remote = [1, 2]

for remote, (host, username) in zip(remote, hosts_users):
    print(remote, host, username)

Output:

1 192.168.0.25 server2
2 192.168.0.26 server3

Leave a Reply