2

In Mule/Dataweave how do I convert/transform a HashMap into a Array. I have got a HashMap whose key & value are dynamic numbers.

Example:

{"3.2" : 1, "22" : 8, "2.0" : 1}

I want to transform it to this structure:

[
  {
    "name": "app-a",
    "value1": 3.2,
    "value2": 1
  },
  {
    "name": "app-a",
    "value1": 22,
    "value2": 8
  },
  {
    "name": "app-a",
    "value1": 2,
    "value2": 1
  }
]

Solution (Thanks to @Sulthony H)

%dw 1.0
%output application/json
---
payload pluck $$ map {
value1: ($ as :string) as :number,
value2: payload[$]
}
gnanagurus
  • 883
  • 1
  • 12
  • 29

2 Answers2

3

In order to transform a HashMap into an Array, I will do the following steps:

  1. Iterate the HashMap by its key using pluck operator in DataWeave: payload pluck $$ map {}
  2. Transform the key as number: value1: ($ as :string) as :number
  3. Get the value based on that key: value2: payload[$]
sulthony h
  • 1,279
  • 1
  • 8
  • 9
1

Another different solution:

%dw 1.0
%output application/json
---
payload map {
    ($ mapObject {
        name: "app-a",
        value1: $$ as :string,
        value2: $
    })
}

1 - Use the map operator to iterate on the list of elements. payload map

2 - Use mapObject on each of the element of your array $ mapObject. With mapObject, $$ refers to the key name, $ refers to the value

3 - print out the values with value1: $$ as :string, value2: $

Even more simple...

payload pluck (
    {
        value1:$$,
        value2:$
    }
)
mario martinez
  • 297
  • 2
  • 11