如何在 json dataweave 中求和值

How to sum value in json dataweave

(Mule 软数据编织 1.0)

我想将 json 中的二级对象加在一起。如果我有这个 json 值

{
    "type": Type1,
    "date" :{
        "day1" : 1,
        "day2" : 2,
        "day3" : 3
    },
    "a" : test
},
{
    "type": Type2,
    "date" :{
        "day1" : 4,
        "day2" : 5,
        "day3" : 6
    },
    "a" : test2
}

如何对 date 中的值求和,以便输出 (totalDate) 如下所示:

{
"type": Type1,
"totalDate" : 6,
"date" :{
      "day1" : 1,
      "day2" : 2,
      "day3" : 3
  },
  "a" : test
},
{
  "type": Type2,
  "totalDate" : 15,
  "date" :{
      "day1" : 4,
      "day2" : 5,
      "day3" : 6
  },
  "a" : test2
}

Map, pluck, sum (mule 4), reduce(骡子 3):

假设您的输入是这样的数组:

[
    {
        "type": "Type1",
        "date" :{
            "day1" : 1,
            "day2" : 2,
            "day3" : 3
        },
        "a" : "test"
    },
    {
        "type": "Type2",
        "date" :{
            "day1" : 4,
            "day2" : 5,
            "day3" : 6
        },
        "a" : "test2"
    }
]

编辑:

在 dataweave 1.0 中,我会这样做:

注意:即使在 mule 应用程序中,输入行也是有效的。将其编辑为错误是不正确的,即使通常没有必要。只是想避免该编辑中的一些错误信息,因为有时有完全正当的理由来定义您的输入。据我所知,他正在读取文件并且没有设置 mime 类型。通过保留该行,它仍将正确处理。

The input directive is not required in some scenarios when the DataWeave execution itself is contextualized and the input derived from said context. For example, in Mule their event concept provides the context, adding inputs such as payload and vars, with their respective MIME type information. After this section, we will avoid the input directive and assume a single input named payload throughout the rest of the tutorial.

更多信息在这里:

https://docs.mulesoft.com/mule-runtime/3.9/dataweave-reference-documentation#document-structure

https://docs.mulesoft.com/mule-runtime/3.9/dataweave-reference-documentation#input-directive

%dw 1.0
%input payload application/json
%output application/json
---
payload map {
  ($),
  totalDate: ($.date pluck $) reduce $+$$
}

唯一的区别是我不依赖求和,因为它不是我可用的函数。 reduce $+$$ 意味着我将我的累加器默认为数组中的第一个数字,然后将其后的每个数字添加到它。这实际上也是 3.9 文档推荐的做法:https://docs.mulesoft.com/mule-runtime/3.9/dataweave-operators#reduce 以获得更详细的解释。


我们可以映射每个对象。我们创建一个新对象,然后使用($)将现有对象解构到其中。从那里,我们创建一个新字段,它将通过从日期对象 ($.date pluck $) 中提取所有值来填充,然后将其放入 sum.

%dw 2.0
output application/json
---
payload map {
    ($),
    totalDate: sum($.date pluck $)
}

Michael 的答案也可以修改为...

%dw 2.0
output application/json
---
payload map ((value, index) -> 
    {
        (value),
        totalDate: sum(valuesOf(value.date))
    }
)

另一种方法

%dw 2.0
output application/json
---
payload map (v0,k0) ->
{
    (v0 ++ (totalDate:(v0.date pluck $) reduce(item,acc) -> item + acc))
}