yq/pkg/yqlib/doc/operators/parent.md

109 lines
1.2 KiB
Markdown
Raw Normal View History

2021-11-23 23:59:19 +00:00
# Parent
Parent simply returns the parent nodes of the matching nodes.
2021-11-23 23:16:48 +00:00
## Simple example
Given a sample.yml file of:
```yaml
a:
nested: cat
```
then
```bash
2022-01-27 06:21:10 +00:00
yq '.a.nested | parent' sample.yml
2021-11-23 23:16:48 +00:00
```
will output
```yaml
nested: cat
```
2021-11-23 23:59:19 +00:00
## Parent of nested matches
2021-11-23 23:16:48 +00:00
Given a sample.yml file of:
```yaml
a:
fruit: apple
2021-11-23 23:59:19 +00:00
name: bob
2021-11-23 23:16:48 +00:00
b:
fruit: banana
2021-11-23 23:59:19 +00:00
name: sam
2021-11-23 23:16:48 +00:00
```
then
```bash
2022-01-27 06:21:10 +00:00
yq '.. | select(. == "banana") | parent' sample.yml
2021-11-23 23:16:48 +00:00
```
will output
```yaml
fruit: banana
2021-11-23 23:59:19 +00:00
name: sam
2021-11-23 23:16:48 +00:00
```
## 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
```
2024-03-11 23:48:42 +00:00
## N-th parent
You can optionally supply the number of levels to go up for the parent, the default being 1.
Given a sample.yml file of:
```yaml
a:
b:
c: cat
```
then
```bash
yq '.a.b.c | parent(2)' sample.yml
```
will output
```yaml
b:
c: cat
```
## N-th parent - another level
Given a sample.yml file of:
```yaml
a:
b:
c: cat
```
then
```bash
yq '.a.b.c | parent(3)' sample.yml
```
will output
```yaml
a:
b:
c: cat
```
2021-11-23 23:16:48 +00:00
## No parent
Given a sample.yml file of:
```yaml
{}
```
then
```bash
2022-01-27 06:21:10 +00:00
yq 'parent' sample.yml
2021-11-23 23:16:48 +00:00
```
will output
```yaml
```