为每个 JSON 数组运行 Python 命令



我正在研究一些 API 自动化脚本,该脚本将从 CLI 导入变量(这用于 Ansible 集成)和另一个从 JSON 文件导入变量的选项(如果该文件存在)。 如果此文件存在,则完全忽略 CLI。

目前,我在一个名为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

我有多个文件需要为不同的任务调用这些变量,例如,需要使用我的api.py文件来提取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']

然后cid以及parameters.py中的其他变量需要在我的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.')

当我运行它时,我可以在使用 CLI 和data.json文件之间切换。当 JSON 文件中存在单个[client]时,该脚本有效,但当有多个时,它仅适用于最后一个[client]示例:data.json

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

使用data.json文件时main.py的输出:Client test2 has been completed.第一个客户端没有做任何事情。我做错了什么?对于Python和一般编程来说相当新,任何帮助将不胜感激。

我看到您在for loop中将值分配给json中的变量。 但是,你看,这里 ->

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

变量刚刚被分配,其他操作正在for loop之外完成 因此,在loopfirst client中被获取并分配给变量。在第二次迭代中,获取next client重新分配相同的变量,值为this new client。 因此,它总是只显示last client的结果。

您需要做的如下:

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

或者,如果您想在其他地方执行这些operations,则可以将这些变量添加到另一种数据类型(如listdict)中,但这会将您带到从json中提取数据的原始情况

最新更新