DataWeave supports the update
operator, which enables you to update specified fields of a data structure with new values.
Overview
This operator is the one to use when you wish to change specific fields on an Object, while keeping all others the same.
Difference Between Update Function and Update Operator in Dataweave
Update Function in Dataweave
To use the update function, we need to import the package dw::util::Values. The other functions available in this package are attr, mask, index, field. The update function can be used to update an element of each object in an array.
Update Operator in Dataweave
Update operator is used to updating specified fields of a data structure with new values. If the requirement is to update an element on some condition, we use the update operator.
example
Here’s an example where update
is used to increase a value and even insert a field using the upserting functionality (!
):
Input
{
"firstName": "Avery",
"lastName": "Chance",
"age": 56,
"occupation": "Physicist"
}
DW Script
%dw 2.0
output json
---
payload update {
case currentAge at .age -> currentAge + 1
case .status! -> "Retired"
}
Output
{
"firstName": "Avery",
"lastName": "Chance",
"age": 57,
"occupation": "Physicist",
"status": "Retired"
}
Notice that you can capture the values into variables, as with currentAge
. This is important because it allows using the value as part of the new one and even evaluating conditions. Let’s see an example:
Input
[
{"name": "Ken (Leandro)", "age": 30},
{"name": "Tomo", "age": 70},
{"name": "Kajika", "age": 10}
]
DW Script
%dw 2.0
output json
---
payload map ((user, index) -> user update {
case name at .name if (name == "Tomo") -> name ++ " (Christian)"
})
Output
[
{"name": "Ken (Leandro)", "age": 30},
{"name": "Tomo (Christian)", "age": 70},
{"name": "Kajika", "age": 10}
]
So far we’ve worked with flat Objects, but the update
operator allows selecting fields no matter how nested the Object structure is.
Follow Me
If you like my post please follow me to read my latest post on programming and technology.
Leave a Comment