Introduction
In my
last post I covered the topic of removing null object and empty strings from JSON payload. That solution is only good for two level of objects. If the JSON hierarchy has multiple level, then it would not work. In that case, we need to use recursion. This post will show the solution for this purpose.
Sample Input
[
{
"first_name" : "Gary",
"middle_name" : "",
"last_name" : "Liu",
"address" : {
"street" : {
"number" : "",
"name" : ""
},
"city" : null,
"zip" : null
}
}
]
Desired 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 {
(($$): skipNulls($)) when ($ != null and $ != "")
}
%function skipEmpty(o) o
unless o is :object
otherwise o mapObject {
(($$): skipEmpty($)) when ($ != {} and $ != '')
}
---
payload map ((person) -> {
(skipEmpty(person mapObject {
($$): skipNulls($)
})
)
})
Key Learning Points
In the solution given here, I used the recursion as the following:
%function skipNulls(o) o
unless o is :object
otherwise o mapObject {
(($$): skipNulls($)) when ($ != null and $ != "")
}
This demonstrates that dataweave functions allow us to use the recursion concept. The code provide here is not perfect yet. There is a bug I am working on.
Hi Gray, Your posts are helpful and gave good insight of simple tricks. Thanks for your posts, Much appropriated..!
ReplyDeleteGlad it is help. Thanks
DeleteIt is nice blog Thank you porovide importent information for
ReplyDeletedesired outputs key learning posts and i am searching for same information to save my time thank you so much....
AWS Online Training Hyderabad