How to remove objects with null values from Mule payload? 👩🏼‍💻

We are not using skipNullOn="everywhere" on the %output directive and removed null fields using a function instead. This makes us to completely remove the object if the values are null using a function.

The Dataweave function (in both solutions) works because mapObject allows us to loop over the object fields, and include them in the result object only if they meet a certain condition.




How to remove an object from payload if it has null values


Input Payload:

{
"address": {
"city": "vtz",
"street_name": "lawsons colony",
"country_code": "SMC",
"landmark": {
"postal": null,
"state": null
}
}}

Dataweave code:

%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($)
}
)

Output:

{   
"address": {
"city": "bab",
"company_name": "asdast",
"country_code": "sam"
}}

Want to learn Mulesoft and ESB tutorials? Our blog provides best articles on Mule 4Mule 3, Dataweave, Anypoint platform and Anypoint Studio. We provide tutorials on creating mule applications, how to use different connectors, running dataweave code, and solving issues. Let us know if you want to create a tutorial on any Mulesoft Tutorials

Post a Comment

0 Comments