Home > Enterprise >  How to loop through json data with multiple objects
How to loop through json data with multiple objects

Time:06-14

My json file data.json 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

CodePudding user response:

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

CodePudding user response:

if you have json file first you need to read and after that, you can manipulate that data as a python object

import json

with open("data.json") as json_file:
    data = json.load(json_file)

for d in data:
    host = d['host']
    username = d['username']
    path = d['path']
    print(host, username, path)

CodePudding user response:

You can do by using map with zip like

# uncomment following code if data reside in json
# import json
# file = open('path_of_your_json')
# data = json.load(file)
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"}
]

for (host, username, path) in zip(*zip(*map(lambda x: x.values(), data))): 
   print(host, username, path)   
   # whatever you want

zip(*zip(*map(lambda x: x.values(), data))) this line will provide the data in linear way

CodePudding user response:

Since you mentioned specifically that you would like to iterate through the data using zip column wise, here is how you can do that.

Say the json file name is SO.json

Load the json object in the variable data.

import json
f = open(r'C:\Users\YYName\Desktop\Temp\SO.json')
data = json.load(f)

Now you can iterate through the values using zip and through columns. Load the json data in a pandas dataframe.

import pandas as pd
df = pd.DataFrame(data)
for host,username in zip(df["host"] ,df["username"]):
    print(host, username)

Assuming remote to be of same length as the number of rows in your json. You can now do

for remotes,host,username in zip(remote , df["host"] ,df["username"]):
    print(remotes, host, username)
  • Related