I am working on transforming my payload. I have got the situation here.
Input payload looks like this below one:-
{
"address": {
"city": "bab",
"company_name": "asdast",
"country_code": "sam",
"location": {
"city": null,
"state": null
}
}}
I used %output application/json skipNullOn = "everywhere"
it returns me JSON like below
{
"address": {
"city": "bab",
"company_name": "asdast",
"country_code": "sam",
"location": { }
}}
But I don't want to have empty location object if all fields in location objects are empty.I am expecting something like this
{
"address": {
"city": "bab",
"company_name": "asdast",
"country_code": "sam"
}}
Using the below dataweave function, you can ignore any empty values, objects or arrays that you want! You can update the case v is Array| Object | Null | "" to include any other cases you would like to skip over when outputting your payload.
Skip on Null This can be set through an attribute in the output directive named skipNullOn, which can be set to three different values: elements, attributes or everywhere. There are two ways(may be more) that nulls can be checked in data weave code .
Let's see how to skip all the null values in DataWeave transform node. There are 3 different values that you can specify the skipNullOn i.e. objects, arrays, or everywhere. You can see the zip field is not there in the output because we have used skipNullOn to skip all the null values.
This is a recursive solution I arrived at after the direct approach seemed hard 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 the direct approach 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 dropped skipNullOn="everywhere"
on the %output
directive, and removed null fields in a function instead. This allows us to make sure the nulls get removed before we check if the containing object is empty.
The 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With