Can traverse straight from parent operator (parent.blah)

This commit is contained in:
Mike Farah 2024-09-06 12:46:23 +10:00
parent dff0122481
commit 1846006082
3 changed files with 29 additions and 2 deletions

View File

@ -37,6 +37,25 @@ fruit: banana
name: sam name: sam
``` ```
## Get parent attribute
Given a sample.yml file of:
```yaml
a:
fruit: apple
name: bob
b:
fruit: banana
name: sam
```
then
```bash
yq '.. | select(. == "banana") | parent.name' sample.yml
```
will output
```yaml
sam
```
## N-th parent ## N-th parent
You can optionally supply the number of levels to go up for the parent, the default being 1. You can optionally supply the number of levels to go up for the parent, the default being 1.

View File

@ -517,7 +517,7 @@ func parentWithLevel() yqAction {
prefs := parentOpPreferences{Level: level} prefs := parentOpPreferences{Level: level}
op := &Operation{OperationType: getParentOpType, Value: getParentOpType.Type, StringValue: value, Preferences: prefs} op := &Operation{OperationType: getParentOpType, Value: getParentOpType.Type, StringValue: value, Preferences: prefs}
return &token{TokenType: operationToken, Operation: op}, nil return &token{TokenType: operationToken, Operation: op, CheckForPostTraverse: true}, nil
} }
} }
@ -525,7 +525,7 @@ func parentWithDefaultLevel() yqAction {
return func(rawToken lexer.Token) (*token, error) { return func(rawToken lexer.Token) (*token, error) {
prefs := parentOpPreferences{Level: 1} prefs := parentOpPreferences{Level: 1}
op := &Operation{OperationType: getParentOpType, Value: getParentOpType.Type, StringValue: getParentOpType.Type, Preferences: prefs} op := &Operation{OperationType: getParentOpType, Value: getParentOpType.Type, StringValue: getParentOpType.Type, Preferences: prefs}
return &token{TokenType: operationToken, Operation: op}, nil return &token{TokenType: operationToken, Operation: op, CheckForPostTraverse: true}, nil
} }
} }

View File

@ -21,6 +21,14 @@ var parentOperatorScenarios = []expressionScenario{
"D0, P[b], (!!map)::{fruit: banana, name: sam}\n", "D0, P[b], (!!map)::{fruit: banana, name: sam}\n",
}, },
}, },
{
description: "Get parent attribute",
document: `{a: {fruit: apple, name: bob}, b: {fruit: banana, name: sam}}`,
expression: `.. | select(. == "banana") | parent.name`,
expected: []string{
"D0, P[b name], (!!str)::sam\n",
},
},
{ {
description: "N-th parent", description: "N-th parent",
subdescription: "You can optionally supply the number of levels to go up for the parent, the default being 1.", subdescription: "You can optionally supply the number of levels to go up for the parent, the default being 1.",