yq icon indicating copy to clipboard operation
yq copied to clipboard

Add support for Conditionals and Comparisons 'if-then-else'

Open kenjones-cisco opened this issue 6 years ago • 7 comments

Add support for Conditionals and Comparisons 'if-then-else'

if A then B else C end will act the same as B if A produces a value other than false or null, but act the same as C otherwise.

Checking for false or null is a simpler notion of “truthiness” than is found in Javascript or Python, but it means that you’ll sometimes have to be more explicit about the condition you want: you can’t test whether, e.g. a string is empty using if .name then A else B end, you’ll need something more like if (.name | length) > 0 then A else B end instead.

If the condition A produces multiple results, then B is evaluated once for each result that is not false or null, and C is evaluated once for each false or null.

More cases can be added to an if using elif A then B syntax.

kenjones-cisco avatar Sep 27 '17 02:09 kenjones-cisco

Has it been implemented?

rLitto avatar Aug 06 '21 15:08 rLitto

Has it been implemented?

No:

yq e --null-input 'if true then 2 else 3 end'
Error: Parsing expression: Lexer error: could not match text starting at 1:1 failing at 1:3.
	unmatched text: "if"

@mikefarah I think you closed this by accident.

CyberShadow avatar Dec 22 '21 17:12 CyberShadow

really odd that we don't have conditionals, i see all related issues are closed without any comments https://github.com/mikefarah/yq/issues/94 https://github.com/mikefarah/yq/issues/96 https://github.com/mikefarah/yq/issues/97

@mikefarah can you please comment on these? is it going to be implemented, if not can we get any rationale?

76creates avatar Mar 15 '22 08:03 76creates

Oops - sorry I closed a bunch of issues back then that didn't seem to have anyone interested in them (then didn't see the comments). Re opening.

mikefarah avatar Mar 15 '22 09:03 mikefarah

There is a work around detailed here in the docs:

https://mikefarah.gitbook.io/yq/usage/tips-and-tricks#logic-without-if-elif-else

sorvis avatar Sep 23 '22 18:09 sorvis

There is a work around detailed here in the docs:

https://mikefarah.gitbook.io/yq/usage/tips-and-tricks#logic-without-if-elif-else

How can I use it as an expression in a .map?

sarimarton avatar Jan 22 '23 03:01 sarimarton

It sure would be nice to have more than one demo. Maybe something more complex perhaps.

planeiii-te avatar Mar 01 '23 22:03 planeiii-te