VOOZH about

URL: https://dzone.com/articles/mule-4-how-to-pass-dynamic-values-for-keys-in-key

⇱ Mule 4 - How to Pass Dynamic Values for "keys" in Key-Value Pair


Related

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.

By Feb. 08, 21 · Tutorial
Likes
Comment
Save
30.1K Views

Join the DZone community and get the full member experience.

Join For Free

Hello 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  : 

Java




x


1
%dw 2.0
2
output application/java
3
---
4
{
5
"message" : vars.message
6
}



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:

Java




x


1
%dw 2.0
2
output application/json
3
var a = "message"
4
---
5
{
6
"$(a)" : payload
7
}


The above syntax returns:

JSON




xxxxxxxxxx
1


1
{
2
    "message": "Hello Muleys"
3
}



If you want dynamic keys for an array of objects,

then you can use like ($.xyz) you need to wrap in ().

Java




xxxxxxxxxx
1
15


1
%dw 2.0
2
output application/json
3
 
 
4
var a = "OrderInformation"
5
var orders = [
6
{orderId : 134 , orderName :  "Soap"},
7
{orderId : 222 , orderName :  "Tumbler"},
8
{orderId : 389 , orderName :  "NoteBook"}
9
]
10
--- 
11
"$(a)" : orders map {
12
($.orderId) : $.orderName
13
}
14
 
 
15
 
 


Result :

JSON




xxxxxxxxxx
1
13


1
{
2
  "OrderInformation": [
3
   {
4
      "134": "Soap"
5
   },
6
   {
7
      "222": "Tumbler"
8
   },
9
   {
10
      "389": "NoteBook"
11
   }
12
 ]
13
}



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!


Pass (software)

Opinions expressed by DZone contributors are their own.

Related

  • Coordinating Threads Using CountDownLatch
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • MuleSoft APIkit Router - QueryParam and Header Strict Validation Configuration
  • Multi-Threaded Geo Web Crawler In Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: