fgiraldeau
fgiraldeau

Reputation: 2734

jq ignores else clause

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?

Upvotes: 3

Views: 248

Answers (1)

choroba
choroba

Reputation: 241768

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.

Upvotes: 4

Related Questions