【问题标题】:Combining the elements of array and reformatting the output组合数组的元素并重新格式化输出
【发布时间】:2019-05-09 09:12:34
【问题描述】:

我有一个输入 JSON,我想使用 Mule 的 dataweave 2.0 对其进行转换。

下面是输入的 JSON。

[
   {
     "data1": {
                "role": "analyst",
                "name": "ABC"
     },
     "data2": {
                "role": "analyst",
                "name": "DEF"
     }
  },
  {
     "data1": {
                "role": "RM",
                "name": "PQRS"
     },
     "data2": {
                "role": "analyst",
                "name": "QWE"
     }
  }
]

我们希望输出如下:

[
  {
     "role": "analyst",
     "name": "ABC"
  },
  {
     "role": "analyst",
     "name": "DEF"
  },
  {
     "role": "RM",
     "name": "PQRS"
  },
  {
     "role": "analyst",
     "name": "QWE"
  }
]

我尝试了使用 map、pluck 和 flatten 的不同选项,但无法得到解决方案。请帮我解决这个问题。

【问题讨论】:

    标签: mule dataweave mule4


    【解决方案1】:

    如果您想保持订单,您可以:

    1) 遍历带有reduce 的元素,并为数组中的每个对象累积data1data2

    %dw 2.0
    output application/json
    ---
    payload reduce (item, acc = []) -> (acc << item.data1 << item.data2)
    

    2) 使用map,为数组中的每个元素创建一个中间数组,其中包含data1data2,然后是flatten

    %dw 2.0
    output application/json
    ---
    flatten (payload map (item) -> [item.data1, item.data2])
    

    【讨论】:

      【解决方案2】:

      如果响应对象的顺序很重要:

      %dw 2.0
      output application/json
      ---
      flatten (payload map (flatten $))
      

      如果顺序不重要:

      %dw 2.0
      output application/json
      ---
      payload.data1 ++ payload.data2
      

      【讨论】:

        猜你喜欢
        • 2013-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-15
        • 1970-01-01
        • 1970-01-01
        • 2021-01-09
        相关资源
        最近更新 更多