yq/pkg/yqlib/doc/operators/create-collect-into-object.md
Mike Farah 13d1bbb45f
Generic ast (#1829)
Remove dependency on yaml.Node for internal AST representation. Yaml decoder is now just another decoder.
2023-10-18 12:11:53 +11:00

1.2 KiB

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

yq --null-input '{}'

will output

{}

Wrap (prefix) existing object

Given a sample.yml file of:

name: Mike

then

yq '{"wrap": .}' sample.yml

will output

wrap:
  name: Mike

Using splat to create multiple objects

Given a sample.yml file of:

name: Mike
pets:
  - cat
  - dog

then

yq '{.name: .pets.[]}' sample.yml

will output

Mike: cat
Mike: dog

Working with multiple documents

Given a sample.yml file of:

name: Mike
pets:
  - cat
  - dog
---
name: Rosey
pets:
  - monkey
  - sheep

then

yq '{.name: .pets.[]}' sample.yml

will output

Mike: cat
Mike: dog
---
Rosey: monkey
Rosey: sheep

Creating yaml from scratch

Running

yq --null-input '{"wrap": "frog"}'

will output

wrap: frog

Creating yaml from scratch with multiple objects

Running

yq --null-input '(.a.b = "foo") | (.d.e = "bar")'

will output

a:
  b: foo
d:
  e: bar