Search code examples
bashyq

Collecting results into a map from a yaml file with yq, values are unexpectedly null


I am trying to get the results of the following structure from a yaml file

applications:
  a:
    enabled: true
    persistence: true
  b:
    enabled: true
    persistence: true
  c:
    enabled: true
    persistence: false

Using yq by mikefarah v4.30.4:

yq '.applications | to_entries | .[] |select(.value.enabled == true) | .key: .value.persistence' manifest.yml

But I get this output:

[{a: null}, {b: null}, {c: null}]

Trying other examples I get the following result

yq '.applications | to_entries | .[] |select(.value.enabled == true) | {.key: {.persistence: .value.persistence}}' manifest.yml
a:
  null: true
b:
  null: true
c:
  null: false

The result should be

a: true, b: true, c: false

Solution

  • The most immediate problem could be solved by more parens ((.key: .value.persistence) instead of .key: .value.persistence), but to get a single map as output, you should use a reducer:

    yq '
    (.applications
    | to_entries
    | .[]
    | select(.value.enabled == true)
    ) as $i ireduce({}; .[$i.key] = $i.value.persistence)
    ' manifest.yml
    

    ...yields as output:

    a: true
    b: true
    c: false