-1

I need to get the total price of the order in Dataweave.

<?xml version='1.0' encoding='UTF-8'?>
<Orders>
  <Order id="10001">
    <ProductId id="P001">P-001</ProductId>
    <ProductName>Samsung 40Inch TV</ProductName>
    <Category id="C001">Samsung TV</Category>
    <Price>399</Price>
    <Quantity>5</Quantity>
  </Order>
  <Order id="10001">
    <ProductId id="P002">P-002</ProductId>
    <ProductName>Samsung 32Inch TV</ProductName>
    <Category id="C001">Samsung TV</Category>
    <Price>299</Price>
    <Quantity>5</Quantity>
  </Order>
</Orders>

I've tried the following dataweave without success:

%dw 2.0
output application/json
---
{
 "totalCost": sum(payload.Orders.*Order.Price)  
}
aled
  • 21,330
  • 3
  • 27
  • 34
  • 1
    What do you mean without success. It does work for me – machaval Mar 26 '22 at 12:10
  • This is not the answer what I need. I need total cost of the order. Need to get the sum value of whole orders cost. – Poornima Vithanage Mar 26 '22 at 18:13
  • 1
    And what is the actual result or error your recibing? As part of your question you should explain actual vs expected values and provide examples. As part of the explanation define what is the total cost of the order. – aled Mar 27 '22 at 02:15

2 Answers2

0

The script seems to be doing what it is expected, ie sum all the Prices in Orders. Since it is not clear in the question I will guess that you need to calculate instead the 'total cost' of an order, assuming it is its price multiplied by quantity. For that you have to first map each Order to its price * quantity, before calculating the sum:

%dw 2.0
output application/json
---
{
    "totalCost": sum(payload.Orders.*Order map ($.Price * $.Quantity))
}

Output:

{
  "totalCost": 3490
}
aled
  • 21,330
  • 3
  • 27
  • 34
0

the below code will generate total price of each order

%dw 2.0
output application/json
---
payload.Orders.*Order map(
    "totalCost": $.Price * $.Quantity
)

output:-

[
  {
    "totalCost": 1995
  },
  {
    "totalCost": 1495
  }
]

if you want total cost for all the orders then use below script

%dw 2.0
output application/json
---
"totalCost" : sum(payload.Orders.*Order map(
    $.Price * $.Quantity
))

output:-

{
  "totalCost": 3490
}
  • The second solution, which seems to be what was requested, is exactly the same that my previous answer. – aled Apr 26 '22 at 11:55