使用jq更新对象中其他字段标识的数组元素



目标

我想在kubeconfig文件的当前活动clusters条目中添加一个proxy-url字段。";活动的";簇由";活动的";上下文,其本身由顶级密钥current-context标识。简化后,JSON对象看起来像:

{
"clusters":[
{
"name":"cluster1",
"field":"field1"
},
{
"name":"cluster2",
"field":"field2"
}
],
"contexts":[
{
"name":"context1",
"context": {
"cluster":"cluster1"
}
},
{
"name":"context2",
"context": {
"cluster":"cluster2"
}
}
],
"current-context": "context1"
}

我想从更新cluster1clusters条目

{
"name":"cluster1",
"field":"field1"
}

{
"name":"cluster1",
"field":"field1",
"proxy-url":"my-url"
}

第一次尝试

jq '. as $o
| $o."current-context" as $current_context_name
| $o.contexts[] | select(.name == $current_context_name) as $context
| $o.clusters[] | select(.name == $context.context.cluster)
| .proxy_id |= "my-url"'

给我

{
"name": "cluster1",
"field": "field1",
"proxy_id": "my-url"
}

--太棒了!但我也需要剩下的东西。

括号几乎起作用

使用圆括号,我可以取回整个对象&添加一个";代理url";字段添加到活动上下文,但我无法更进一步地更新活动cluster。此过滤器:

jq '(. as $o
| $o."current-context" as $current_context_name
| $o.contexts[] | select(.name == $current_context_name)
| ."proxy-url")
|= "my-url"'

铸币厂:

{
"clusters": [...],  // omitted for brevity, unchanged
"contexts": [
{
"name": "context1",
"context": {
"cluster": "cluster1"
},
"proxy-url": "my-url"  // tada!
},
{...}  // omitted for brevity, unchanged
],
"current-context": "context1"
}

尝试更进一步(更新由context标识的cluster(:

jq '(. as $o
| $o."current-context" as $current_context_name
| $o.contexts[] | select(.name == $current_context_name) as $context
| $o.clusters[] | select(.name == $context.context.cluster)
| ."proxy-url")
|= "my-url"'

给我以下错误:

jq: error (at <stdin>:26): Invalid path expression near attempt to access element "clusters" of {"clusters":[{"name":"clus...
exit status 5

如何使用$context.context.cluster结果来更新相关的clusters条目?我不明白为什么这种方法适用于向contexts添加某些内容,而不适用于clusters

脏溶液

我可以拼凑出一个新的CCD_ 12条目&将其与顶级对象合并:

jq '. as $o
| $o."current-context" as $current_context_name
| $o.contexts[] | select(.name == $current_context_name) as $context
| $o + {"clusters": [($o.clusters[] | select(.name == $context.context.cluster)."proxy-url" |= "my-url")]}

但这感觉有点脆弱。

此解决方案使用INDEX构造检索活动集群,然后直接设置新字段,而不修改上下文:

jq '
INDEX(.contexts[]; .name)[."current-context"].context.cluster as $cluster
| (.clusters[] | select(.name == $cluster))."proxy-url" = "my-url"
'
{
"clusters": [
{
"name": "cluster1",
"field": "field1",
"proxy-url": "my-url"
},
{
"name": "cluster2",
"field": "field2"
}
],
"contexts": [
{
"name": "context1",
"context": {
"cluster": "cluster1"
}
},
{
"name": "context2",
"context": {
"cluster": "cluster2"
}
}
],
"current-context": "context1"
}

演示

相关内容

  • 没有找到相关文章

最新更新