Find nested key-value pair in yaml

Viewed 906

I'm trying to use yq to find if a key-value pair exists in a yaml. Here's an example yaml:

houseThings:
  - houseThing:
      thingType: chair
  - houseThing:
      thingType: table
  - houseThing:
      thingType: door

I just want an expression that evaluates to true (or any value, or exits with zero status) if the key-value pair of thingType: door exists in the yaml above.

The best I can do so far is find if the value exists by recursively walking all nodes and checking their value: yq eval '.. | select(. == "door")' my_file.yaml which returns door. But I also want to make sure thingType is its key.

1 Answers

You could use the select statement under houseThing as

yq e '.houseThings[].houseThing | select(.thingType == "door")' yaml

or do a recursive look for it

yq e '.. | select(has("thingType")) | select(.thingType == "door")' yaml
Related