Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an empty map from YAML using yq

Tags:

yaml

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?

like image 229
André Micocci Avatar asked Sep 12 '25 01:09

André Micocci


1 Answers

mikefarah/yq

For a generic approach you can use the command

yq e 'del(.. | select(tag == "!!map" and length == 0))'

to remove all empty objects in the input.

Change !!map with !!seq if you want to do the same for empty arrays.


kislyuk/yq

Remove empty objects: yq -y 'del(.. | select(objects and length == 0))'

Remove empty arrays: yq -y 'del(.. | select(arrays and length == 0))'

Remove empty objects, arrays and strings: yq -y 'del(.. | select(length == 0))'

like image 196
jpseng Avatar answered Sep 13 '25 19:09

jpseng