DEV Community

Cover image for Methods for Handling Null Values in DataWeave
Anil K
Anil K

Posted on • Edited on

Methods for Handling Null Values in DataWeave

In the world of data transformation, dealing with null values in JSON objects is a common challenge. Luckily, DataWeave provides straightforward techniques to tackle this issue effectively. Let's explore a few practical methods.

Using SkipNullOn Attribute

DataWeave's skipNullOn attribute lets us control how null values are handled during transformation. Whether we want to skip them in elements, attributes, or everywhere, this feature allows for precise customization.

Example

Input (Object with null value)

{
    "fname": "elon",
    "lname": null
}
Enter fullscreen mode Exit fullscreen mode

DataWeave Script

%dw 2.0
output application/json  skipNullOn="everywhere"
---
payload
Enter fullscreen mode Exit fullscreen mode

Output (Object without null value)

{
    "fname": "elon"
}
Enter fullscreen mode Exit fullscreen mode

Conditional Logic

By employing simple conditional statements, we can include or exclude fields based on their null status. This helps ensure that our output remains relevant and concise.

Example

Input (Object with null value)

{
    "mule_id": "100100",
    "object_id": null,
    "dev_id": "101101"
}
Enter fullscreen mode Exit fullscreen mode

DataWeave Script

%dw 2.0
var route_id = null
output application/json
---
{
    "mule_id": "100100",
    ("object_id": route_id) if (route_id != null),
    "dev_id": "101101"
}
Enter fullscreen mode Exit fullscreen mode

Output

{
    "mule_id": "100100",
    "dev_id": "101101"
}
Enter fullscreen mode Exit fullscreen mode

Utilizing MapObject and FilterObject Functions

DataWeave offers handy functions like mapObject and filterObject, which allow us to manipulate objects and filter out null values efficiently. These functions streamline our code and produce cleaner output.

Example (Using MapObject)

Input (Object with null value)

{
    "fname": "elon",
    "lname": null
}
Enter fullscreen mode Exit fullscreen mode

DataWeave Script

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

Output (Object without null value)

{
    "fname": "elon"
}
Enter fullscreen mode Exit fullscreen mode

Example (Using FilterObject)

Input (Object with null value)

{
    "fname": "elon",
    "lname": null
}
Enter fullscreen mode Exit fullscreen mode

DataWeave Script

%dw 2.0
output application/json
---
payload filterObject $ != null
Enter fullscreen mode Exit fullscreen mode

Output (Object without null value)

{
    "fname": "elon"
}
Enter fullscreen mode Exit fullscreen mode

By incorporating these techniques into your workflows, you can streamline your data transformations and ensure cleaner outputs. Happy coding!

Top comments (0)