diff --git a/pkg/yqlib/doc/Variable Operators.md b/pkg/yqlib/doc/Variable Operators.md new file mode 100644 index 00000000..25c706a9 --- /dev/null +++ b/pkg/yqlib/doc/Variable Operators.md @@ -0,0 +1,58 @@ +For more complex scenarios, variables can be used to hold values of expression to be used in other expressions. + +## Single value variable +Given a sample.yml file of: +```yaml +a: cat +``` +then +```bash +yq eval '.a as $foo | $foo' sample.yml +``` +will output +```yaml +cat +``` + +## Multi value variable +Given a sample.yml file of: +```yaml +- cat +- dog +``` +then +```bash +yq eval '.[] as $foo | $foo' sample.yml +``` +will output +```yaml +cat +dog +``` + +## Using variables as a lookup +Example taken from [jq](https://stedolan.github.io/jq/manual/#Variable/SymbolicBindingOperator:...as$identifier|...) + +Given a sample.yml file of: +```yaml +"posts": + - "title": Frist psot + "author": anon + - "title": A well-written article + "author": person1 +"realnames": + "anon": Anonymous Coward + "person1": Person McPherson +``` +then +```bash +yq eval '.realnames as $names | .posts[] | {"title":.title, "author": $names[.author]}' sample.yml +``` +will output +```yaml +title: Frist psot +author: Anonymous Coward +title: A well-written article +author: Person McPherson +``` + diff --git a/pkg/yqlib/doc/headers/Variable Operators.md b/pkg/yqlib/doc/headers/Variable Operators.md new file mode 100644 index 00000000..887b7f7e --- /dev/null +++ b/pkg/yqlib/doc/headers/Variable Operators.md @@ -0,0 +1 @@ +For more complex scenarios, variables can be used to hold values of expression to be used in other expressions. diff --git a/pkg/yqlib/operator_variables_test.go b/pkg/yqlib/operator_variables_test.go index 1d65c71b..b0fe20a1 100644 --- a/pkg/yqlib/operator_variables_test.go +++ b/pkg/yqlib/operator_variables_test.go @@ -23,7 +23,8 @@ var variableOperatorScenarios = []expressionScenario{ }, }, { - description: "Using variables as a lookup", + description: "Using variables as a lookup", + subdescription: "Example taken from [jq](https://stedolan.github.io/jq/manual/#Variable/SymbolicBindingOperator:...as$identifier|...)", document: `{"posts": [{"title": "Frist psot", "author": "anon"}, {"title": "A well-written article", "author": "person1"}], "realnames": {"anon": "Anonymous Coward", @@ -40,4 +41,5 @@ func TestVariableOperatorScenarios(t *testing.T) { for _, tt := range variableOperatorScenarios { testScenario(t, &tt) } + documentScenarios(t, "Variable Operators", variableOperatorScenarios) }