Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading