Updated: Sep 4
I had this use-case where I had to make sure all the values inside an array were not empty. By “empty,” I’m referring to an empty string (“”), a null value (null), or even an empty array (). There were some cases when I would receive a null value instead of an array. The array could only contain strings or nulls, but not objects. However, I’ll be adding tests to check for empty objects as well.
Note: The term “null” refers to a null value, whereas “Null” refers to the data type. The same rule applies to string/String, array/Array, and object/Object. I can have an empty array (), which is of the type Array, or a string “abc,” which is of the type String.
In this series of posts, I explain 6 different approaches to achieve (almost) the same output using different DataWeave functions/operators. As we advance through the posts, the functions will become easier to read, and the logic will have fewer flaws.
Part 2: Using sizeOf, filter, isEmpty, and default.
I use the DataWeave Playground throughout these articles. You can follow this post to set up a local Docker image (no previous Docker experience is needed), or you can also open a new Mule project and use the Transform Message component.
Note: You can also use the online DataWeave Playground tool from this link, if available.
Building the solution
I’ll create an array to start building and testing this solution:
%dw 2.0 output application/json --- ["notEmpty", "", null]
Step 1: We’ll use the “filter” function, followed by “isEmpty” to retrieve the empty items from the array.
["notEmpty", "", null] filter isEmpty($)
Compared to the solution in the previous post, which was using “groupBy” to retrieve all the empty values, we can get the same result in one step instead of two.
Step 2: As we did in the previous solution, we need to count how many values are in this array ([“”, null]). We’ll be using the “sizeOf” function as well.
sizeOf(["notEmpty", "", null] filter isEmpty($))