3

I would like to search and replace a specific value in a json line-based data using jq and keep the object unmodified if the match is false.

Considering the following input.json:

{"foo":{"bar":"one"}}
{"foo":{"bar":"two"}}

I tried the following statement, but the else clause is ignored, and therefore lines that don't match are lost:

jq -c '. | if (select(.foo.bar == "one")) then .foo.bar |= "ok" else . end' input.json

produces result:

{"foo":{"bar":"ok"}}

The following command produces the right output:

jq -c '(. | select(.foo.bar == "one")).foo.bar = "ok"' input.json

desired output:

{"foo":{"bar":"ok"}}
{"foo":{"bar":"two"}}

Why the first command fails to output the object . in the else clause?

peak
  • 105,803
  • 17
  • 152
  • 177
fgiraldeau
  • 2,384
  • 1
  • 19
  • 12
  • Does this answer your question? [Select objects based on value of variable in object using jq](https://stackoverflow.com/questions/18592173/select-objects-based-on-value-of-variable-in-object-using-jq) – blurfus Apr 07 '21 at 18:33
  • 1
    No, this answer was using select and actually we have to use just a if statement as indicated by the accepted answer. Thanks! – fgiraldeau Apr 07 '21 at 19:34

1 Answers1

4

Don't use select:

. | if .foo.bar == "one" then .foo.bar |= "ok" else . end

select is useful for filtering, but it doesn't return a false value if there's nothing to select, it doesn't return anything.

choroba
  • 231,213
  • 25
  • 204
  • 289