Search code examples
yamlyq

How can I separate items extracted from a YAML document into separate documents?


I'm trying to extract items from an array in a YAML document, and have each item become its own standalone document, and print all documents together separated by ---.

For example, assuming the following given YAML document:

kind: testDoc
items:
- kind: subDoc
  key: value1
- kind: subDoc
  key: value2
- kind: subDoc
  key: value3

I'd like to receive this:

kind: subDoc
key: value1
---
kind: subDoc
key: value2
---
kind: subDoc
key: value3

I've tried this: yq '.items[]' < test.yaml which yields this result:

kind: subDoc
key: value1
kind: subDoc
key: value2
kind: subDoc
key: value3

Is there a way to separate each result into a separate YAML document in the output?


Solution

  • With mikefarah/yq (tested on v4.35.1), you can use the split_doc function (see the manual).

    yq '.items[] | split_doc' test.yaml 
    

    With kislyuk/yq (tested on v3.2.3), use the -y option (see the documentation).

    yq -y '.items[]' test.yaml
    

    With itchyny/gojq (tested on v0.12.13), use the --yaml-input and --yaml-output options (see the documentation).

    gojq --yaml-input --yaml-output '.items[]' test.yaml
    

    All of them have the same output (but gojq additionally sorts the keys):

    kind: subDoc
    key: value1
    ---
    kind: subDoc
    key: value2
    ---
    kind: subDoc
    key: value3