How to output a field only when present in the input message?
Let us see how to populate a field when it is present in the input else remove the field. To avoid populating null values in the output we can add a condition that checks if the value is present in the input or not. We also have an option to add skipNullOn="everywhere" in the DataWeave header which removes keys with null values across the full payload.
Example without using if :
Below is a simple JSON array with three objects. If you observe the second object does not have the field role while the first and third object does. After applying the transformation, the second object is populated with the "role" field as null. To avoid this we can add an if condition to the field which is explained in the below scenario.

Example using skipNullOn:
To avoid populating keys with null values in the output, simply add skipNullOn="everywhere" in the header part of the dataweave script. However, this addition removes all the fields with null values
You also might like: Remove objects with null values from payload

To overcome this situation we can make use of if condition which is explained below
Also see: Filter keys with multiples values in array from JSON message using Dataweave
Example with if condition:
After adding if condition to the "role" field, the output of the second object in the JSON array does not contain "role" field

Want to publish an article here? We would like to post on your behalf. Please submit your articles at hello@designgrows.com along with your social profile links.
0 Comments