Search code examples
yamlyq

How to remove an empty map from YAML using yq


I need to remove an empty map from a YAML, using YQ
Sometimes this map may have values, and sometimes this will appears empty.

My YAML code looks like this:

apiVersion: route.openshift.io/v1
kind: Route
metadata:
  annotations: {}
  creationTimestamp: "2021-03-24T13:16:10Z"

I need to remove annotations: {}

My desired output:

apiVersion: route.openshift.io/v1
kind: Route
metadata:
  creationTimestamp: "2021-03-24T13:16:10Z"

Anybody can helps me?


Solution

  • You can delete the annotations map when its length is 0. Using mikefarah/yq, this can be done as below (verfied on yq version 4.9.6)

    yq e 'del(.metadata.annotations | select(length==0))' yaml
    

    Note: Since 4.18.1, yq's eval/e command is the default command and no longer needs to be specified.