Skip to content
Advertisement

Running Python commands for each JSON array

I am working on some API automation scripting that will import variables from the CLI (this is used for Ansible integration) and another option to import the variables from a JSON file, if that file exists. If this file exists, the CLI is completely ignored.

Currently, I have my variables set up in a file named parameters.py:

jsondata = os.path.exists('data.json')
if jsondata == True:
    with open('data.json') as data_file:    
        data = json.load(data_file)
        for client in data['clients']:
            hostname = client['client']['hostname']
            type = client['client']['type']
            position = client['client']['position']
else:
   parser = argparse.ArgumentParser(description = 'Variables')
   parser.add_argument('--hostname')
   parser.add_argument('--type')
   parser.add_argument('--position')
   args = parser.parse_args(sys.argv[1:])
   hostname = args.hostname
   type = args.type
   position = args.position

I have multiple files that need to call upon these variables for different tasks, for example it needs to be used my api.py file to pull an ID

if parameters.hostname:
    query1 = {'name': parameters.hostname}
    v1 = requests.get(
        'http://test.com',
         params=query1)
    v2 = v1.status_code
    v3= v2.text
    v4= json.loads(v3)
    cid = v4['data'][0]['id']

Then the cid as well as other variables from parameters.py needs to be used in my main.py

payload = {
  "name": str(parameters.hostname),
  "cid": int(api.cid),
  "type": str(parameters.type),
  "custom_fields": {}
}

if parameters.position:
    payload['position'] = parameters.position
register = requests.post(
    'test.com',
    data=json.dumps(payload))
regstatus = register.status_code
if regstatus == 201:
    print (f'Client {parameters.hostname} has been completed.')

When I run this, I am able to switch between using the CLI and a data.json file. The script works when there is a single [client] in the JSON file, but when there’s multiple, it only works on the last [client] Example: data.json

{
    "clients": [
        {
        "client": {
        "hostname": "test",
        "type": 3,
         }
        },
        {
        "client": {
            "hostname": "test2",
            "type": 1,
            "position": "front",
        }
        }
           ]
    }

Output from main.py when using a data.json file: Client test2 has been completed. nothing is being done with the first client. What am I doing wrong? Fairly new to Python and programming in general, any help would be appreciated.

Advertisement

Answer

I see that you assign values to variables from json in a for loop. But, you see, here – >

for client in data['clients']:
   hostname = client['client']['hostname']
   type = client['client']['type']
   position = client['client']['position']

variable are just getting assigned and other operations are being done outside the for loop So, in loop first client is fetched and assigned to variables. and in second iteration next client is fetched and same variables gets reassigned with value of this new client. Hence, it is only showing result for last client always.

What you need to do is as follow :

for client in data['clients']:
   hostname = client['client']['hostname']
   type = client['client']['type']
   position = client['client']['position']
   #<do some operations here>

Or if you want to do these operations elsewhere then you can add these variables in another datatype like list or dict but this takes you to the original situation of extracting data from a json

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement