Added get key examples

This commit is contained in:
Mike Farah 2020-11-26 11:20:53 +11:00
parent 5205f01248
commit 13679e51e2
5 changed files with 54 additions and 1 deletions

1
pkg/yqlib/doc/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.zip

View File

@ -1,4 +1,7 @@
The path operator can be used to get the traversal paths of matching nodes in an expression. The path is returned as an array, which if traversed in order will lead to the matching node.
You can get the key/index of matching nodes by using the `path` operator to return the path array then piping that through `.[-1]` to get the last element of that array, the key.
## Map path
Given a sample.yml file of:
```yaml
@ -15,6 +18,21 @@ will output
- b
```
## Get map key
Given a sample.yml file of:
```yaml
a:
b: cat
```
then
```bash
yq eval '.a.b | path | .[-1]' sample.yml
```
will output
```yaml
b
```
## Array path
Given a sample.yml file of:
```yaml
@ -32,6 +50,22 @@ will output
- 1
```
## Get array index
Given a sample.yml file of:
```yaml
a:
- cat
- dog
```
then
```bash
yq eval '.a.[] | select(. == "dog") | path | .[-1]' sample.yml
```
will output
```yaml
1
```
## Print path and value
Given a sample.yml file of:
```yaml

0
pkg/yqlib/doc/aa.md Normal file
View File

View File

@ -1 +1,3 @@
The path operator can be used to get the traversal paths of matching nodes in an expression. The path is returned as an array, which if traversed in order will lead to the matching node.
The path operator can be used to get the traversal paths of matching nodes in an expression. The path is returned as an array, which if traversed in order will lead to the matching node.
You can get the key/index of matching nodes by using the `path` operator to return the path array then piping that through `.[-1]` to get the last element of that array, the key.

View File

@ -13,6 +13,14 @@ var pathOperatorScenarios = []expressionScenario{
"D0, P[a b], (!!seq)::- a\n- b\n",
},
},
{
description: "Get map key",
document: `{a: {b: cat}}`,
expression: `.a.b | path | .[-1]`,
expected: []string{
"D0, P[a b -1], (!!str)::b\n",
},
},
{
description: "Array path",
document: `{a: [cat, dog]}`,
@ -21,6 +29,14 @@ var pathOperatorScenarios = []expressionScenario{
"D0, P[a 1], (!!seq)::- a\n- 1\n",
},
},
{
description: "Get array index",
document: `{a: [cat, dog]}`,
expression: `.a.[] | select(. == "dog") | path | .[-1]`,
expected: []string{
"D0, P[a 1 -1], (!!int)::1\n",
},
},
{
description: "Print path and value",
document: `{a: [cat, dog, frog]}`,