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
}
]
2
Answers
Within
with_entries
, you only need to assign the computed value (.key | length
) to.value
using=
. The value of.key
remains unaltered.Demo
You want
Explanation follows.
is roughly equivalent to
So you are effectively doing
3 | length
and4 | length
. When given a number,length
produces the number. So these produce3
and4
respectively.You want the length of the key.
Similarly,
can be seen as
Since the key is already a string, that’s just
And this does nothing at all.