coderz.py

Keep Coding Keep Cheering!

Update Operator Examples

Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.

Example

Versions prior to Mule 4.3 require the following syntax to increase the age value in myInput by one without recreating the entire object:

Source

%dw 2.0
var myInput = {
    "name": "Ken",
    "lastName":"Shokida",
    "age": 30
}
output application/json
---
myInput mapObject ((value,key) ->
    if(key as String == "age")
       {(key): value as Number + 1}
    else
       {(key): value} )

In Mule 4.3, the update operator simplifies the syntax:

Source

%dw 2.0
var myInput = {
    "name": "Ken",
    "lastName":"Shokida",
    "age": 30
}
output application/json
---
myInput update {
    case age at .age -> age + 1
}

Both DataWeave scripts return the same result:

Output

{
  "name": "Ken",
  "lastName": "Shokida",
  "age": 31
}

With update, casting or iterating through all the key-value pairs is not necessary.

The update syntax is as follows:

<value_to_update> update {
    case <variable_name> at <update_expression>[!]? [if(<conditional_expression>)]? -> <new value>
    ...
}

Source

%dw 2.0
output application/json
---
payload map ((item) ->
    item.ServiceDetails update {
        case Designation at .Designation if (Designation == "Clerk") ->  "Assistant Manager"
})

Output

[
  {
    "Designation": "Assistant Manager",
    "DOJ": "Sept 20 1998"
  },
  {
    "Designation": "Assistant Manager",
    "DOJ": "Sept 20 2000"
  },
  {
    "Designation": "Accountant",
    "DOJ": "Sept 20 2015"
  }
]

  • value_to_update represents the original value to update.
  • update_expression is the selector expression that matches a value in value_to_update.
  • variable_name is the name of the variable to bind to the matched update_expression value.
  • new_value is the expression with the new value.
  • [if(<conditional_expression>)]? If conditional_expression returns true, the script updates the value. Use of a conditional expression is optional.
  • [!] marks the selector as an upsert. If the expression doesn’t find a match, the ! makes the update operator create all the required elements and insert the new value.
  • update_expression supports multiple case expressions.

Note
The update operator doesn’t mutate the existing value. Instead, the operator creates a new value with the updated expressions.

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement