skip to Main Content

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


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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search