Fragan
Fragan

Reputation: 892

JSON object Ignore null

Im kinda new to MuleSoft and DataWeave and im trying to make a JSON Object with only not null values from another JSON object.

Let's say this is my JSON array :

{
    str1 : "String 1",
    str2 : "String 2",
    str3 : null,
    str4 : "String 4",
}

I want to make a copy of that JSON array but without str3, so result should looks like this :

{
    str1 : "String 1",
    str2 : "String 2",
    str4 : "String 4",
}

Anyone can help me out with this ? or atleast lead me to the solutions ?

Regards

Upvotes: 2

Views: 1217

Answers (3)

user3078986
user3078986

Reputation:

Here's yet another way:

%dw 2.0
output application/json
var o = {
    str1 : "String 1",
    str2 : "String 2",
    str3 : null,
    str4 : "String 4",
}
---
o filterObject $ != null

Here's the filterObject documentation

Pick the one you like :)

Upvotes: 3

aled
aled

Reputation: 25872

For an object you can transform all the attributes that are not null:

%dw 2.0
output application/json
---
payload mapObject (($$): $ ) if (!($ == null))

Upvotes: 3

Jorge Garcia
Jorge Garcia

Reputation: 1383

There are 2 possible approaches:

Using the writer property skipNullOn as mentioned here

output application/json skipNullOn="everywhere"
---
payload

Programatically with an if condition (this is for field by field mapping)

var b = null
---
{
    a: 1,
    (b: b) if b != null,
    c: 3
}

Upvotes: 4

Related Questions