0

This is VERY similar to Update one value in array of dicts, using jq

I have a foo.json and I want to update AAA to AAA-MY-SUFFIX. Basically, I want to get the current value (AAA), and then add a suffix to it.

[ { "Key": "Name", "Value": "awesome" }, { "Key": "role", "Value": "AAA" } ]

From the previous question, I can REPLACE the value of AAA using this:

cat foo.json | jq '(.[] | select(.Key == "role") | .Value) |= "-MY_SUFFIX"'

But I want to APPEND a suffix to the existing value, not completely replace it.

Something like this (but it doesn't work, of course):

cat tags.json | jq '(.[] | select(.Key == "role") | .Value) |= .Value + "-MY_SUFFIX"'

I feel I'm SO close, but I just can figure it out :(

peak
  • 105,803
  • 17
  • 152
  • 177
grayaii
  • 2,241
  • 7
  • 31
  • 47

2 Answers2

2

Close indeed. You could simply replace .Value + "-MY_SUFFIX" by

. + "-MY_SUFFIX"

Or better yet, use +=, as in: ... += "-MY_SUFFIX"

Personally, I'd use the filter:

map(if .Key == "role" then .Value += "-MY_SUFFIX" else . end)

(Actually, the stated requirements would accord better with using the suffix "-MY-SUFFIX" :-)

peak
  • 105,803
  • 17
  • 152
  • 177
1

After much fooling around, I think I got it:

cat tags.json | jq '(.[] | select(.Key == "role") | .Value) |= (. + "- MY_SUFFIX")'
grayaii
  • 2,241
  • 7
  • 31
  • 47