Mule 4 - How to Pass Dynamic Values for "keys" in Key-Value Pair
Learn how to pass dynamic values for "keys" in key-value pair in Mulesoft DataWeave 2.0.
Join the DZone community and get the full member experience.
Join For FreeHello Muleys,
You might have quite often encountered a situation where you need to have dynamic "keys" in a key-value pair.
We know that we can pass dynamic values directly using the syntax like below :
%dw 2.0
output application/java
---
{
"message" : vars.message
}
But even the key "message" has to be dynamic. Then what's the syntax we have to use?
Simple! -
Define a local variable,
"$(a)" - Just wrap within double quotes and give your local var within ()
Double quotes are very important. Or else you will have a syntactical error.
Also its () not {} . There's a difference between $() and ${}
${} is used to retrieve property value. Whereas $() is used to retrieve dynamic value.
Eg:
x
%dw 2.0
output application/json
var a = "message"
---
{
"$(a)" : payload
}
The above syntax returns:
xxxxxxxxxx
{
"message": "Hello Muleys"
}
If you want dynamic keys for an array of objects,
then you can use like ($.xyz) you need to wrap in ().
xxxxxxxxxx
%dw 2.0
output application/json
var a = "OrderInformation"
var orders = [
{orderId : 134 , orderName : "Soap"},
{orderId : 222 , orderName : "Tumbler"},
{orderId : 389 , orderName : "NoteBook"}
]
---
"$(a)" : orders map {
($.orderId) : $.orderName
}
Result :
xxxxxxxxxx
{
"OrderInformation": [
{
"134": "Soap"
},
{
"222": "Tumbler"
},
{
"389": "NoteBook"
}
]
}
So basically 2 different syntaxes for dynamic keys.
One: When you want to use the local variable as the key-value - "$(a)"
Two: When you want to use the array of values as keys - ($.xyz)
Here's the video for the same :
Simple and Short!
Happy Learning!
Opinions expressed by DZone contributors are their own.
Comments