This is a recursive solution that I came to after the direct approach seemed difficult to understand:
%dw 1.0 %output application/json %function acceptable(value) ( (value default {}) != {} ) %function filterKeyValue(key, value) ( ((key): value) when acceptable(value) ) %function removeFields(o) o unless o is :object otherwise o mapObject (filterKeyValue($$, removeFields($))) --- removeFields(payload)
Here's a direct approach that I started with:
%dw 1.0 %output application/json %function skipNulls(o) o unless o is :object otherwise o mapObject { (($$): $) when ($ != null) } %function skipEmpty(o) o mapObject { (($$): $) when ($ != {}) } --- address: skipEmpty(payload.address mapObject { ($$): skipNulls($) } )
Note that we omitted skipNullOn="everywhere" in the %output directive and instead removed the null fields in the function. This allows us to make sure that zeros are removed before we check to see if the containing object is empty.
The function (in both solutions) works because mapObject allows us to mapObject over the fields of an object and include them in the result of the object only if they satisfy a certain condition.
source share