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

155 lines
1.6 KiB
Markdown
Raw Normal View History

2021-11-03 04:00:58 +00:00
# Keys
Use the `keys` operator to return map keys or array indices.
2023-05-09 03:51:21 +00:00
## Map keys
Given a sample.yml file of:
```yaml
2023-05-30 05:05:28 +00:00
dog: woof
cat: meow
2023-05-09 03:51:21 +00:00
```
then
```bash
yq 'keys' sample.yml
```
will output
```yaml
- dog
- cat
```
## Array keys
Given a sample.yml file of:
```yaml
2023-05-30 05:05:28 +00:00
- apple
- banana
2023-05-09 03:51:21 +00:00
```
then
```bash
yq 'keys' sample.yml
```
will output
```yaml
- 0
- 1
```
## Retrieve array key
Given a sample.yml file of:
```yaml
2023-05-30 05:05:28 +00:00
- 1
- 2
- 3
2023-05-09 03:51:21 +00:00
```
then
```bash
yq '.[1] | key' sample.yml
```
will output
```yaml
1
```
## Retrieve map key
Given a sample.yml file of:
```yaml
a: thing
```
then
```bash
yq '.a | key' sample.yml
```
will output
```yaml
a
```
## No key
Given a sample.yml file of:
```yaml
{}
```
then
```bash
yq 'key' sample.yml
```
will output
```yaml
```
## Update map key
Given a sample.yml file of:
```yaml
a:
x: 3
y: 4
```
then
```bash
yq '(.a.x | key) = "meow"' sample.yml
```
will output
```yaml
a:
meow: 3
y: 4
```
## Get comment from map key
Given a sample.yml file of:
```yaml
a:
# comment on key
x: 3
y: 4
```
then
```bash
yq '.a.x | key | headComment' sample.yml
```
will output
```yaml
comment on key
```
2022-09-30 00:27:35 +00:00
## Check node is a key
Given a sample.yml file of:
```yaml
2023-05-09 03:51:21 +00:00
a:
b:
- cat
c: frog
2022-09-30 00:27:35 +00:00
```
then
```bash
yq '[... | { "p": path | join("."), "isKey": is_key, "tag": tag }]' sample.yml
```
will output
```yaml
- p: ""
isKey: false
tag: '!!map'
- p: a
isKey: true
2023-05-09 03:51:21 +00:00
tag: '!!str'
2022-09-30 00:27:35 +00:00
- p: a
2023-05-09 03:51:21 +00:00
isKey: false
tag: '!!map'
2023-05-30 01:58:41 +00:00
- p: a.b
2023-05-09 03:51:21 +00:00
isKey: true
tag: '!!str'
- p: a.b
isKey: false
tag: '!!seq'
- p: a.b.0
isKey: false
tag: '!!str'
2023-05-30 01:58:41 +00:00
- p: a.c
isKey: true
tag: '!!str'
2023-05-09 03:51:21 +00:00
- p: a.c
2022-09-30 00:27:35 +00:00
isKey: false
tag: '!!str'
```