API 请求的 JSON 格式,仅当在 Python 中给出值时才需要行
我正在开发一个使用 Python 中的命令参数推送 API 请求的程序。我的变量保存如下:
parser.add_argument('--ilo', help = "iLO IP address for client")
args = parser.parse_args(sys.argv[1:])
ilo = args.ilo or "0"
对于我的 JSON 格式,我有以下内容:
test = {
"name": hostname,
"device_type": type,
"device_role": role,
"tenant": tenant,
"platform": platform,
"serial": chassis_serial,
"site": site,
"location": location,
"rack": rack,
"position": position,
"face": face,
"status": status,
"custom_fields": {
"management_ip_address": f'{ilo}'
}
}
此请求特别不需要所有这些行。不需要某些变量,例如“ilo”和“position”。有什么方法可以制作一个条件语句,即如果给出 --variable 则将“variable”:variable 行添加到 JSON,如果不是则不执行任何操作并且不添加该行?任何帮助将不胜感激!
I am working on a program that pushes API requests using command parameters from Python. My variables are held as follows:
parser.add_argument('--ilo', help = "iLO IP address for client")
args = parser.parse_args(sys.argv[1:])
ilo = args.ilo or "0"
For my JSON formatting, I have the following:
test = {
"name": hostname,
"device_type": type,
"device_role": role,
"tenant": tenant,
"platform": platform,
"serial": chassis_serial,
"site": site,
"location": location,
"rack": rack,
"position": position,
"face": face,
"status": status,
"custom_fields": {
"management_ip_address": f'{ilo}'
}
}
This request in particular does not need all of these lines. Some variables such as 'ilo' and 'position' are not needed. Is there any way that I can make a conditional statement that if --variable is given then add the "variable": variable line to the JSON and if it's not then do nothing and don't add that line? Any help would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最初保留这些字段,然后根据需要将它们添加到
if
语句中。Leave those fields out initially, then add them in an
if
statement if needed.