API 请求的 JSON 格式,仅当在 Python 中给出值时才需要行

发布于 2025-01-11 13:09:55 字数 729 浏览 0 评论 0原文

我正在开发一个使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

第七度阳光i 2025-01-18 13:09:55

最初保留这些字段,然后根据需要将它们添加到 if 语句中。

test = {
  "name": hostname,
  "device_type": type,
  "device_role": role,
  "tenant": tenant,
  "platform": platform,
  "serial": chassis_serial,
  "site": site,
  "location": location,
  "rack": rack,
  "face": face,
  "status": status,
  "custom_fields": {}
}

if position:
    test['position'] = position
if ilo:
    test['custom_fields']['management_ip_address'] = str(ilo)

Leave those fields out initially, then add them in an if statement if needed.

test = {
  "name": hostname,
  "device_type": type,
  "device_role": role,
  "tenant": tenant,
  "platform": platform,
  "serial": chassis_serial,
  "site": site,
  "location": location,
  "rack": rack,
  "face": face,
  "status": status,
  "custom_fields": {}
}

if position:
    test['position'] = position
if ilo:
    test['custom_fields']['management_ip_address'] = str(ilo)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文