在Dataweave中获取总和值

Getting sum value in Dataweave

我需要在 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>

我尝试了以下数据编织但没有成功:

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

脚本似乎在做预期的事情,即对订单中的所有价格求和。由于问题不清楚,我猜你需要计算订单的 'total cost',假设它是价格乘以数量。为此,您必须先将每个订单映射到其价格 * 数量,然后再计算总和:

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

输出:

{
  "totalCost": 3490
}

下面的代码将生成每个订单的总价

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

输出:-

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

如果您想要所有订单的总费用,请使用以下脚本

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

输出:-

{
  "totalCost": 3490
}