表格数据到嵌套JSON

时间:2019-08-21 18:02:54

标签: mule-studio anypoint-studio dataweave mulesoft

我正在尝试使用MuleSoft将表格查询输出转换为嵌套JSON。我的查询输出如下:

----------------------------------
Customer |  Order   |   Items
----------------------------------
C       |   Order1  |   Itm1
C       |   Order1  |   Itm2
C       |   Order2  |   Itm1
C       |   Order2  |   Itm4
C       |   Order3  |   Itm3
C       |   Order3  |   Itm4

并使用Mule4 dataweave尝试在流动的JSON输出中将其转换:

Customer: C
Orders: {
            Order1:{
                Items: {                  
                  Item: Item1
                  Item: Item2
                }
            }
            Order2:{
                Items: {                  
                  Item: Item1
                  Item: Item4
                }
            }

            Order3:         

}

到目前为止,我没有运气尝试过以下代码:

%dw 2.0
output application/json
---

    payload map ((st, stindex) -> {
        Customer:   st.Customer,

        Orders: payload filter(($.Customer == st.Customer) and  ($.Order == st.Order)) map ((f, fIndex) ->{

            Order: f.Order      

            Items : payload filter (($.ItemName == f.ItemName) and ($.Order == f.Order)) map ((i, iIndex) -> {

                item: i.ItemName
            })

        })

    })

似乎我错过了一些重要的事情。感谢您的帮助!!

1 个答案:

答案 0 :(得分:0)

我需要一个多级groupBy(),mapObjects和一个reduce()作为项目。

%dw 2.0
output application/json
---
(payload map {
    Customer: $.Customer,
    Order: $.Order,
    Items: $.Items
} groupBy (item) -> item.Customer) 
    mapObject ((value, key, index) -> { 
        Customer : key, 
        Orders: (value groupBy (orders)->orders.Order) 
            mapObject ((value1, key1,  index1) -> {
                    "$(key1)": value1 reduce ((item, accumulator={}) -> accumulator ++ {Item: item.Items} )
            }     
            )
        }
      )

输出:

{
  "Customer": "C",
  "Orders": {
    "Order2": {
      "Item": "Itm1",
      "Item": "Itm4"
    },
    "Order1": {
      "Item": "Itm1",
      "Item": "Itm2"
    },
    "Order3": {
      "Item": "Itm3",
      "Item": "Itm4"
    }
  }
}

脚本的缩进是不好的,但现在修复它为时已晚。