-1

I am new to Mule and I want to convert below JSON array value type as number when itemType is downloadSpeed.

Input

   {
      "itemType": "DD-Offer",
      "id": "DD-1",
      "items": [
        {
          "itemType": "downloadSpeed",
          "value": "1000 mpbs"
        },
        {
          "itemType": "uploadSpeed",
          "value": "3 mpbs"
        },
        {
          "itemType": "downloadSpeed",
          "value": "500 mpbs"
        }
      ]
   }
    

Code

    %dw 2.0
    output application/json
    var reward = payload.items filter((item)->item.itemType=='downloadSpeed')

---
reward

Expected Result

{
  "itemType": "DD-Offer",
  "id": "DD-1",
  "items": [
    {
      "itemType": "downloadSpeed",
      "value": 1000
    },
    {
      "itemType": "uploadSpeed",
      "value": "3 mpbs"
    },
    {
      "itemType": "downloadSpeed",
      "value": 500
    }
  ]
}
Krish
  • 4,166
  • 11
  • 58
  • 110
  • I do not understand. The reward and installation both are already in a single array. and you said you want it in a single array?? can you clarify it? – Harshank Bansal Oct 20 '22 at 11:22
  • The script that was shared in the question seems not useful at all to achieve the expected output. – aled Oct 20 '22 at 11:53
  • The title line makes no sense with respect to the input/outputs described in the question. Please update it. – aled Oct 20 '22 at 12:12
  • Hi Sorry , Now i have updated title – Krish Oct 20 '22 at 12:45

1 Answers1

0

You need only to understand what is the outcome you want and express in DataWeave terms. In this case you want to update only payload.items so we use the update operator to change only the items. Since items is a list we use map() to transform it. Inside the mapping, if the element has the expected type we replace it by finding the value before the first space using Jump to substringBefore() and convert it to a number. If it wasn't of the type it returns the existing value as is.

%dw 2.0
output application/json
import substringBefore from dw::core::Strings
---
payload  update {
        case .items ->  
            $ map {
                itemType: $.itemType,
                value: 
                    if ($.itemType == "downloadSpeed")           
                        substringBefore($.value, " ") as Number 
                    else 
                        $.value
            }
}

Output:

{
  "itemType": "DD-Offer",
  "id": "DD-1",
  "items": [
    {
      "itemType": "downloadSpeed",
      "value": 1000
    },
    {
      "itemType": "uploadSpeed",
      "value": "3 mpbs"
    },
    {
      "itemType": "downloadSpeed",
      "value": 500
    }
  ]
}
aled
  • 21,330
  • 3
  • 27
  • 34