Isaac Abramowitz
Isaac Abramowitz

Reputation: 540

Perform the same operation on multiple JSON fields using JQ

I'm trying to change the values of multiple fields in a JSON object using JQ. However, I want to perform the same operation on each of these fields. I accomplished this, but the way I did seems redundant.

jq '.fieldOne |= . * 3 | .fieldTwo |= . * 3 | ...'

Is there a way of doing something along the lines of this: (not exactly this because JQ won't work like that)

jq '(.fieldOne | .fieldTwo | ...) |= . * 3'

Upvotes: 2

Views: 348

Answers (1)

peak
peak

Reputation: 116957

Thanks to the magic of jq, you could just write:

(.fieldOne, .fieldTwo) |= .*3

More generically, here are two other approaches.

multiop/2

# If the input is an object, $fields should be an array of key names
# If the input is an array, $fields should be an array of integers
def multiop($fields; f):
  if $fields|length == 0 then .
  else .[$fields[0]] |= f
  | multiop($fields[1:]; f)
  end;

multiop(["fieldOne", "fieldTwo"]; . * 3)

Or, if you want the operation applied to all fields:

multiop( keys_unsorted; .*3)

triple/1

def triple(f): f |= . * 3;

triple(.fieldOne, .fieldTwo)

Upvotes: 2

Related Questions