jq 更新 json 文件中的布尔值

jq update boolean value in json file

我正在尝试使用 jq 更新 json 文件中的布尔值。

我的json文件是这样的:

{
  "kind": "KubeletConfiguration",
  "apiVersion": "kubelet.config.k8s.io/v1beta1",
  "address": "0.0.0.0",
  "authentication": {
    "anonymous": {
      "enabled": true
    },
    "webhook": {
      "cacheTTL": "2m0s",
      "enabled": true
    },
    "x509": {
      "clientCAFile": "/etc/kubernetes/pki/ca.crt"
    }
  },
  "authorization": {
    "mode": "Webhook",
    "webhook": {
      "cacheAuthorizedTTL": "5m0s",
      "cacheUnauthorizedTTL": "30s"
    }
  },
....omitted

我想用布尔值 false

更新 .authentication.anonymous.enabled 值

我试过以下方法:

jq --arg new false '.authentication.anonymous.enabled |= $new' config.json

这会将值更新为 false 但它是以字符串而不是布尔值的形式进行的。如下:

{
  "kind": "KubeletConfiguration",
  "apiVersion": "kubelet.config.k8s.io/v1beta1",
  "address": "0.0.0.0",
  "authentication": {
    "anonymous": {
      "enabled": "false"
    },
    "webhook": {
      "cacheTTL": "2m0s",
      "enabled": true
    },
    "x509": {
      "clientCAFile": "/etc/kubernetes/pki/ca.crt"
    }
  },
  "authorization": {
    "mode": "Webhook",
    "webhook": {
      "cacheAuthorizedTTL": "5m0s",
      "cacheUnauthorizedTTL": "30s"
    }
  },
....omitted

如何将其更新为布尔值(值周围没有引号)?

对 JSON 参数使用 --argjson。此外,您在这里只需要赋值运算符 =,因为 RHS 的计算不依赖于 LHS 上下文。

jq --argjson new false '.authentication.anonymous.enabled = $new' config.json

Demo

如果你只想切换那个字段,你可以不带参数和变量:

jq '.authentication.anonymous.enabled |= not' config.json

Demo