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

89 lines
1.1 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.
2022-02-06 03:39:46 +00:00
{% hint style="warning" %}
Note that versions prior to 4.18 require the 'eval/e' command to be specified. 
`yq e <exp> <file>`
{% endhint %}
2021-11-03 04:00:58 +00:00
## 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
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
```