【问题标题】:format json output jq格式json输出jq
【发布时间】:2021-04-16 11:27:41
【问题描述】:

我正在 Kubernetes 中部署 redis-commander。我正在为Redis-Commander 创建一个配置连接文件。我的 bash 脚本中有一个命令,用于根据链接获取连接文件所需的参数。通过 sentinel 管理在 redis-commander 和 1 个 redis 服务器之间进行本地连接就好了,但在非产品中还有更多,所以我需要配置下面的命令以获得所需的 json 输出。

这个命令

kubectl get svc --selector='app.kubernetes.io/component=sentinel' --all-namespaces -o json |
jq -r '
.items[]
   | {label:"my-label",
   sentinels: [{host: (.metadata.name + "."
   + .metadata.namespace + "."
   + "svc" + "."
   + "cluster" + "."
   + "local"),port: .spec.ports[0].port}],
   sentinelName:"mymaster",
   dbIndex: 0
   }
| {connections: [.]}'

有类似这样的输出(我已经更改了名称部分):

{
  "connections": [
    {
      "label": "my-label",
      "sentinels": [
        {
          "host": "name1.development.svc.cluster.local",
          "port": 26379
        }
      ],
      "sentinelName": "mymaster",
      "dbIndex": 0
    }
  ]
}
{
  "connections": [
    {
      "label": "my-label",
      "sentinels": [
        {
          "host": "name2.development.svc.cluster.local",
          "port": 26379
        }
      ],
      "sentinelName": "mymaster",
      "dbIndex": 0
    }
  ]
}
{
  "connections": [
    {
      "label": "my-label",
      "sentinels": [
        {
          "host": "name3.staging.svc.cluster.local",
          "port": 26379
        }
      ],
      "sentinelName": "mymaster",
      "dbIndex": 0
    }
  ]
}

我想要达到的输出是这样的:

{
  "connections": [
    {
      "label": "my-label",
      "sentinels": [
        {
          "host": "name1.development.svc.cluster.local",
          "port": 26379
        },
        {
          "host": "name2.development.svc.cluster.local",
          "port": 26379
        },
        {
          "host": "name3.staging.svc.cluster.local",
          "port": 26379
        }
      ],
      "sentinelName": "mymaster",
      "dbIndex": 0
    }
  ]
}

没有多次使用jq,所以任何指针将不胜感激。

【问题讨论】:

    标签: json jq kubectl redis-sentinel


    【解决方案1】:

    map 与 .items 一起使用可能是一种更好的方法,如下所示:

    .items
    | {
        label: "my-label",
        sentinels: map(
          { host: (.metadata.name + "."
              + .metadata.namespace + "."
              + "svc" + "."
              + "cluster" + "."
              + "local"),
            port: .spec.ports[0].port
          } ),
        sentinelName: "mymaster",
        dbIndex: 0
      }
    | {connections: [.] }
    
    

    【讨论】:

      猜你喜欢
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 2020-03-05
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多