You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jq解析kubectl jsonpath输出中JSON格式的Annotations

解析K8s Annotations并展开JSON格式内容

高效替代循环的jq命令

不用手动遍历数组索引,直接一次性处理所有资源条目,自动识别并展开JSON格式的注释值:

kubectl get XXXX -ojson | jq -r '
.items[] | .metadata.annotations | to_entries[] | 
if .value | fromjson? != null then
  "\(.key):\n" + (.value | fromjson | tostring | indent(2))
else
  "\(.key)=\(.value)"
end'

命令核心逻辑说明

  • .items[]:遍历所有资源条目,省去手动循环${i}的繁琐
  • .metadata.annotations | to_entries[]:将annotations的键值对转换为{key: "...", value: "..."}结构并逐个处理
  • fromjson? != null:尝试将注释值解析为JSON,成功则进入展开分支
  • 展开分支:先输出注释键,换行后用indent(2)格式化JSON内容,提升可读性
  • 普通分支:对非JSON格式的注释,保持key=value的原样输出

效果示例

针对你提供的注释内容,最终输出会呈现为:

test.bob.k8s.elastic.co/token=622fb4bd-e5f9-46e5-a73b-80b9d0fad43a
kubectl.kubernetes.io/last-applied-configuration:
  {
    "apiVersion": "agent.k8s.elastic.co/v1alpha1",
    "kind": "Agent",
    "metadata": {
      "annotations": {},
      "name": "test-agent",
      "namespace": "default"
    },
    "spec": {
      "daemonSet": {
        "podTemplate": {
          "spec": {
            "automountServiceAccountToken": true,
            "containers": [
              {
                "command": [
                  "bash",
                  "-c",
                  "#!/usr/bin/env bash\nset -e\nif [[ -f /mnt/test-internal/test-association/default/bob/certs/ca.crt ]]; then\n  cp /mnt/test-internal/test-association/default/bob/certs/ca.crt /usr/local/share/ca-certificates\n  update-ca-certificates\nfi\n/usr/bin/tini -- /usr/local/bin/docker-entrypoint -e\n"
                ],
                "name": "agent"
              }
            ],
            "securityContext": {
              "runAsUser": 0
            },
            "serviceAccountName": "test-agent"
          }
        }
      },
      "testServerRef": {
        "name": "test-server"
      },
      "testRef": {
        "name": "bob"
      },
      "mode": "test",
      "version": "1.10.2"
    }
  }

内容的提问来源于stack exchange,提问作者Justin Lim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 23:05:58