yq/operators/create-collect-into-object.md

97 lines
1.2 KiB
Markdown
Raw Normal View History

2021-10-30 03:14:39 +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-28 01:45:43 +00:00
yq --null-input '{}'
2021-10-30 03:14:39 +00:00
```
will output
```yaml
{}
```
## Wrap (prefix) existing object
Given a sample.yml file of:
```yaml
name: Mike
```
then
```bash
2022-01-28 01:45:43 +00:00
yq '{"wrap": .}' sample.yml
2021-10-30 03:14:39 +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-28 01:45:43 +00:00
yq '{.name: .pets.[]}' sample.yml
2021-10-30 03:14:39 +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-28 01:45:43 +00:00
yq '{.name: .pets.[]}' sample.yml
2021-10-30 03:14:39 +00:00
```
will output
```yaml
Mike: cat
Mike: dog
2023-11-23 00:59:14 +00:00
---
2021-10-30 03:14:39 +00:00
Rosey: monkey
Rosey: sheep
```
## Creating yaml from scratch
Running
```bash
2022-01-28 01:45:43 +00:00
yq --null-input '{"wrap": "frog"}'
2021-10-30 03:14:39 +00:00
```
will output
```yaml
wrap: frog
```
2021-11-03 04:00:28 +00:00
## 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
```