yq
yq copied to clipboard
Add support for Conditionals and Comparisons 'if-then-else'
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.
Has it been implemented?
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.
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?
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.
There is a work around detailed here in the docs:
https://mikefarah.gitbook.io/yq/usage/tips-and-tricks#logic-without-if-elif-else
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?
It sure would be nice to have more than one demo. Maybe something more complex perhaps.