Search code examples
terminalyq

yq - make key-value pairs from nested yaml structure


Having the following file structure:

A1:
    B1:
        description: "B1 field"
    B2:
        any-field: 1
        description: "B2 field"
A2:
    B3:
        any-field: 1
    B4:
        any-field: 1
        description: "B4 field"

I would like to get the following result:

B1: "B1 field"
B2: "B2 field"
B4: "B4 field"

So basically I need to filter out object without desired property (B3 in this case) and then map each from .*.* | keys to .*.*.description, but I failed to do it.

yq I am using is the newest (4.27.5) from https://github.com/mikefarah/yq


Solution

  • To go 2-levels deep, you can use the to_entries function twice, and then select the key name and the value containing the .description field

    yq 'to_entries | .[].value | to_entries | 
          map(select(.value | has("description"))) | .[] | {.key: .value.description}' yaml