DW ule子中的json键迭代

时间:2019-02-15 09:35:13

标签: json mule dataweave

我需要满足以下要求才能插入动态json键 需要使用此json键并对其进行迭代 这是我的输入

[  
  {  
    "eventType":"ORDER_SHIPPED",
    "entityId":"d0594c02-fb0e-47e1-a61e-1139dc185657",
    "userName":"educator@school.edu",
    "dateTime":"2010-11-11T07:00:00Z",
    "status":"SHIPPED",
    "additionalData":{  
      "quoteId":"d0594c02-fb0e-47e1-a61e-1139dc185657",
      "clientReferenceId":"Srites004",
      "modifiedDt":"2010-11-11T07:00:00Z",
      "packageId":"AIM_PACKAGE",
      "sbsOrderId":"TEST-TS-201809-79486",
      "orderReferenceId":"b0123c02-fb0e-47e1-a61e-1139dc185987",
      "shipDate_1":"2010-11-11T07:00:00Z",
      "shipDate_2":"2010-11-12T07:00:00Z",
      "shipDate_3":"2010-11-13T07:00:00Z",
      "shipMethod_1":"UPS Ground",
      "shipMethod_3":"UPS Ground3",
      "shipMethod_2":"UPS Ground2",
      "trackingNumber_3":"333",
      "trackingNumber_1":"2222",
      "trackingNumber_2":"221"
    }
  }
]

我需要如下输出

{  
  "trackingInfo":[  
    {  
      "shipDate":"2010-11-11T07:00:00Z",
      "shipMethod":"UPS Ground",
      "trackingNbr":"2222"
    },
    {  
      "shipDate":"2010-11-12T07:00:00Z",
      "shipMethod":"UPS Ground2",
      "trackingNbr":"221"
    },
    {  
      "shipDate":"2010-11-13T07:00:00Z",
      "shipMethod":"UPS Ground3",
      "trackingNbr":"333"
    }
  ]
}

shipdate,shipmethod,trackingnumber可以是n个数字。 如何使用json键进行迭代。

1 个答案:

答案 0 :(得分:2)

首先map进行迭代的数组,然后使用pluck获取键列表。

然后,只要总是有相同数量的shipDate到shipMethod等字段即可。过滤键列表,仅迭代这些字段组合存在的次数。

然后通过使用'shipDate__与索引串联(递增1,因为您的示例从1开始并且dw数组从0开始)动态查找键来构造每个对象的输出:

%dw 2.0
output application/json

---

    payload map ((item, index) -> item.additionalData pluck($$) filter ($ contains 'shipDate')  map ((item2, index2) ->
        using(incIndex=(index2+1 as String)){ 
            "shipDate": item.additionalData[('shipDate_'++ incIndex)],
            "shipMethod": item.additionalData[('shipMethod_'++ incIndex)],
             "trackingNbr": item.additionalData[('trackingNumber_'++ incIndex)],
        }
    )

)

在DW 1.0语法中:

%dw 1.0
%output application/json  
---
payload map ((item, index) -> item.additionalData pluck ($$) filter ($ contains 'shipDate') map ((item2, index2) -> 
    using (incIndex = (index2 + 1 as :string))
      {
        "shipDate": item.additionalData[('shipDate_' ++ incIndex)],
        "shipMethod": item.additionalData[('shipMethod_' ++ incIndex)],
        "trackingNbr": item.additionalData[('trackingNumber_' ++ incIndex)]
      }))

除了:

  • output => %output
  • String => :string