英文:
using jq how can i change the value of a key?
问题
使用jq如何更改键的值?
我试图根据键的长度来更改键的值。但它似乎没有按预期工作。
echo '[{"kiwi": 3 }, {"apple" : 4} ]' | jq 'map(with_entries(.key |= "\(.)", .value |= (. | length)))'
实际输出:
[
{
"kiwi": 3
},
{
"apple": 4
}
]
期望输出 -
[
{
"kiwi": 4
},
{
"apple": 5
}
]
英文:
Using jq how can i change the value of a key?
I am trying to change the value of a key based on the length of the key. But it seems to not work as expected.
echo '[{"kiwi": 3 }, {"apple" : 4} ]' | jq 'map(with_entries(.key |= "\(.)", .value |= (. | length)))'
actual output:
[
{
"kiwi": 3
},
{
"apple": 4
}
]
desired output -
[
{
"kiwi": 4
},
{
"apple": 5
}
]
答案1
得分: 4
在 with_entries
内部,只需要使用 =
将计算得到的值(.key | length
)分配给 .value
。.key
的值保持不变。
map(with_entries(.value = (.key | length)))
[
{
"kiwi": 4
},
{
"apple": 5
}
]
英文:
Within with_entries
, you only need to assign the computed value (.key | length
) to .value
using =
. The value of .key
remains unaltered.
map(with_entries(.value = (.key | length)))
[
{
"kiwi": 4
},
{
"apple": 5
}
]
答案2
得分: 3
你想要
```jq
map( with_entries( .value = ( .key | length ) ) )
解释如下。
.value |= ( . | length )
大致等同于
.value = ( .value | . | length )
所以你实际上是在执行 3 | length
和 4 | length
。当给定一个数字时,length
会产生这个数字。所以这些分别产生 3
和 4
。
你想要的是键的长度。
.value = ( .key | length )
同样地,
.key |= "\(.)"
可以看作
.key = ( .key | "\(.)" )
由于键已经是一个字符串,这实际上是
.key = .key
这实际上什么都不做。```
英文:
You want
map( with_entries( .value = ( .key | length ) ) )
Explanation follows.
.value |= ( . | length )
is roughly equivalent to
.value = ( .value | . | length )
So you are effectively doing 3 | length
and 4 | length
. When given a number, length
produces the number. So these produce 3
and 4
respectively.
You want the length of the key.
.value = ( .key | length )
Similarly,
.key |= "\(.)"
can be seen as
.key = ( .key | "\(.)" )
Since the key is already a string, that's just
.key = .key
And this does nothing at all.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论