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.
2023-04-17 06:20:00 +00:00
## Collect empty object
Running
```bash
yq --null-input '{}'
```
will output
```yaml
{}
```
## Wrap (prefix) existing object
Given a sample.yml file of:
```yaml
2023-05-30 05:05:28 +00:00
name: Mike
2023-04-17 06:20:00 +00:00
```
then
```bash
yq '{"wrap": .}' sample.yml
```
will output
```yaml
2023-05-30 05:05:28 +00:00
wrap:
name: Mike
2023-04-17 06:20:00 +00:00
```
## Using splat to create multiple objects
Given a sample.yml file of:
```yaml
2023-05-30 05:05:28 +00:00
name: Mike
pets:
- cat
- dog
2023-04-17 06:20:00 +00:00
```
then
```bash
yq '{.name: .pets.[]}' sample.yml
```
will output
```yaml
Mike: cat
Mike: dog
```
## Working with multiple documents
Given a sample.yml file of:
```yaml
2023-05-30 05:05:28 +00:00
name: Mike
pets:
- cat
- dog
2023-04-17 06:20:00 +00:00
---
2023-05-30 05:05:28 +00:00
name: Rosey
pets:
- monkey
- sheep
2023-04-17 06:20:00 +00:00
```
then
```bash
yq '{.name: .pets.[]}' sample.yml
```
will output
```yaml
Mike: cat
Mike: dog
2023-05-30 01:34:31 +00:00
---
2023-04-17 06:20:00 +00:00
Rosey: monkey
Rosey: sheep
```
## Creating yaml from scratch
Running
```bash
yq --null-input '{"wrap": "frog"}'
```
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
```