Search code examples
yamlyq

yq v4: delete node based on key-value of child


How can I remove all (parent) nodes with the "type: array" key/value pair using yq v4?

Before:

info:
  title: My API
components:
  schemas:
    pets:
      type: array
      items:
        $ref: "#/components/schemas/pet"
    pet:
      type: object
      properties:
        petName:
          type: string

After:

info:
  title: My API
components:
  schemas:
    pet:
      type: object
      properties:
        petName:
          type: string

I use yq (https://github.com/mikefarah/yq/) version v4.30.8

I tried many yq commands, for example:

yq 'del(.components.schemas.[] | select(. == "array") | parent)' filename.yaml

, but without success.


Solution

  • How can I remove all (parent) nodes with the "type: array" key/value pair

    To reach all items, use .. to recurse down the document tree. To filter for a given key/value pair, name key and value on both sides of the equation.

    yq 'del(.. | select(.type == "array"))' file.yaml
    

    EDIT: How to only consider nodes under .components.schemas?

    If you still want recursion, prepend .. with .components.schemas |. Without recursion, replace .. with .components.schemas[].

    yq 'del(.components.schemas | .. | select(.type == "array"))' file.yaml
    
    yq 'del(.components.schemas[] | select(.type == "array"))' file.yaml