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

JSON formatting for API requests, lines only needed if value is given in 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 ,如果没有,则什么也不做,不添加该行?如有任何帮助,我们将不胜感激!

最初将这些字段保留在外,然后根据需要将它们添加到 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)