Introduction
In the message flow from different end points, many data tributes are null. In particular, if the source data are from database, where a lot of attributes can be null or empty string. In this kind of scenarios, we don't want to put all the null objects and empty strings on the wire. This post explain the procedures to remove the null object or empty string from the message payload.
Sample Input
[ { "first_name" : "Gary", "middle_name" : "", "last_name" : "Liu", "address" : { "street" : null, "city" : null, "zip" : null } } ]
Desire Output
[ { "first_name": "Gary", "last_name": "Liu" } ]
Solution
%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 ($ != {} and $ != '') } --- payload map ((person) -> { (skipEmpty(person mapObject { ($$): skipNulls($) }) ) })
Key Learning Points
This dataweave scripts is not perfect yet. More sophisticated solution will be discussed later. What we can learn from this solution is the following:- mapObject function with conditions, which are using in the functions of skipNulls and skipEmpty.
(($$): $) when ($ != {} and $ != '')
- mapObject is just a function, you can use it in custom defined function as well.
Very informative post for mulesoft developers.You can also visit goformule.com for mulesoft stuff.
ReplyDelete