Search code examples
javamulemule-studioanypoint-studiodataweave

In Mule/Dataweave how do I transform a HashMap into a Array when both key & value are numbers


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[$]
}

Solution

  • 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[$]