Search

Dark theme | Light theme

June 27, 2022

DataWeave Delight: Check Type Of Value

To check if a value is of a certain type in DataWeave we must use the is operator. We must specify the type after the is operator and the value before the is operator. For example to check if the value 42 is a Number we write 42 is Number. The result is a Boolean that is either true or false. In the previous example the result is true.

In the following examples we use is on several types:

Source

%dw 2.0

import every from dw::core::Arrays

// Closed object type with two properties alias and name
// that must have the String type.
type User = {|alias: String,name: String|}

// Helper function to check if argument value
// is an Array type and
// only contains elements of type String.
fun checkArrayString(value: Any): Boolean = 
    (value is Array) and
    ((value as Array) every ((element) -> element is String))

// Literal type.
type Language = "DataWeave" | "Java" | "Groovy" | "Clojure"

output application/json
---
{
    string: "DataWeave" is String,
    not_string: 42 is String,
    
    number: 42 is Number,

    // We can also use the Null type to check.
    null_value: null is Null,

    object: {alias: "mrhaki", name: "Hubert A. Klein Ikkink"} is Object,

    // We can check on our own object type.
    user: {alias: "mrhaki", name: "Hubert"} is User,

    // Only the alias property is valid.
    not_user1: {alias: "mrhaki", firstName: "Hubert", lastName: "Klein Ikkink"} is User,

    // User is a closed object so extra properties 
    // don't make it of type User anymore.
    not_user2: {alias: "mrhaki", name: "Hubert", location: "Tilburg"} is User,

    // Type of alias property is not correct.
    not_user3: {alias: 42, name: "Hubert"} is User,
    
    array: ["one", "two"] is Array,

    // To also check the types of the elements
    // we must use an extra check as defined
    // in the checkArrayString helper function.
    array_string: checkArrayString(["one", "two"]),
    not_array_string: checkArrayString([1, 2]),
    not_array: checkArrayString(42),

    // Literal types are supported.
    language: "DataWeave" is Language,
}

Output

{
  "string": true,
  "not_string": false,
  "number": true,
  "null_value": true,
  "object": true,
  "user": true,
  "not_user1": false,
  "not_user2": false,
  "not_user3": false,
  "array": true,
  "array_string": true,
  "not_array_string": false,
  "not_array": false,
  "language": true
}

Written with DataWeave 2.4.