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"
}}
There is no straight way to do this, You can do something like this
Hope this helps.
This is a recursive solution I arrived at after the direct approach seemed hard to understand:
Here's the direct approach I started with:
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.This worked for me (N.B. Dataweave is from Mule version 3.8):
UPDATE:
So, to inject this in the solution by Ryan above:
I have the simplest and the easiest solution.
Use this function
Unfortunately, none of the solutions worked for me , so I used a second 'transform message' component with below code and used skipNullOn="everywhere" in both the components. This code recursively searches for empty elements(null fields,empty strings,empty arrays and empty objects) and removes it.
Hope it helps.