yq/pkg/yqlib/doc/operators/create-collect-into-object.md

97 lines
1.2 KiB
Markdown
Raw Normal View History

2021-11-03 04:00:58 +00:00
# Create, Collect into Object
This is used to construct objects (or maps). This can be used against existing yaml, or to create fresh yaml documents.
## Collect empty object
Running
```bash
2022-01-27 06:21:10 +00:00
yq --null-input '{}'
2021-11-03 04:00:58 +00:00
```
will output
```yaml
{}
```
## Wrap (prefix) existing object
Given a sample.yml file of:
```yaml
name: Mike
```
then
```bash
2022-01-27 06:21:10 +00:00
yq '{"wrap": .}' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
wrap:
name: Mike
```
## Using splat to create multiple objects
Given a sample.yml file of:
```yaml
name: Mike
pets:
- cat
- dog
```
then
```bash
2022-01-27 06:21:10 +00:00
yq '{.name: .pets.[]}' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
Mike: cat
Mike: dog
```
## Working with multiple documents
Given a sample.yml file of:
```yaml
name: Mike
pets:
- cat
- dog
---
name: Rosey
pets:
- monkey
- sheep
```
then
```bash
2022-01-27 06:21:10 +00:00
yq '{.name: .pets.[]}' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
Mike: cat
Mike: dog
---
2021-11-03 04:00:58 +00:00
Rosey: monkey
Rosey: sheep
```
## Creating yaml from scratch
Running
```bash
2022-01-27 06:21:10 +00:00
yq --null-input '{"wrap": "frog"}'
2021-11-03 04:00:58 +00:00
```
will output
```yaml
wrap: frog
```
## Creating yaml from scratch with multiple objects
Running
```bash
yq --null-input '(.a.b = "foo") | (.d.e = "bar")'
```
will output
```yaml
a:
b: foo
d:
e: bar
```