使用jq如何更改键的值?

huangapple go评论73阅读模式
英文:

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
  }
]

Demo

答案2

得分: 3

你想要

```jq
map( with_entries( .value = ( .key | length ) ) )

解释如下。


.value |= ( . | length )

大致等同于

.value = ( .value | . | length )

所以你实际上是在执行 3 | length4 | length。当给定一个数字时,length 会产生这个数字。所以这些分别产生 34

你想要的是的长度。

.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.

huangapple
  • 本文由 发表于 2023年7月28日 02:05:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定